【问题标题】:JavaFx prevent children from triggering setOnMouseEntered for the parentJavaFx 阻止子级为父级触发 setOnMouseEntered
【发布时间】:2014-09-04 22:27:36
【问题描述】:

一个非常简单的问题,我希望有一个简单的答案。

我有一个有点复杂的自定义节点,它扩展了一个组。

当孩子悬停时,如何防止 JavaFx 为 Group 触发 setOnMouseEntered 事件?

setMouseTransparenthackery 似乎无法解决问题。

【问题讨论】:

  • 你试过设置pickOnBoundsProperty吗?顺便说一句,setMouseTransparent 将设置为节点它的子节点。
  • 我刚试过setPickOnBounds(false/true),可惜没用。

标签: javafx


【解决方案1】:

我做了一个简单的测试应用,组没有得到鼠标事件:

private static final class Foo extends Group {
    Foo() {
        final Rectangle blue = new Rectangle(100, 100, Color.BLUE);
        blue.setLayoutX(50);
        blue.setLayoutY(50);
        blue.setOnMouseEntered(e -> System.out.println("Entered blue"));

        final Rectangle green = new Rectangle(100, 100, Color.GREEN);
        green.setLayoutX(250);
        green.setLayoutY(90);
        green.setOnMouseEntered(e -> System.out.println("Entered green"));

        final Rectangle red = new Rectangle(100, 100, Color.RED);
        red.setLayoutX(100);
        red.setLayoutY(200);
        red.setOnMouseEntered(e -> System.out.println("Entered red"));

        getChildren().addAll(blue, green, red);
    }
}

@Override
public void start(final Stage primaryStage) throws Exception {
    final Pane root = new AnchorPane();
    final Foo foo = new Foo();
    root.getChildren().add(foo);
    final Scene scene = new Scene(root);
    primaryStage.setScene(scene);
    primaryStage.show();
}

public static void main(String[] args) {
    launch(args);
}

这是因为它执行了鼠标拾取:

Node#contains 实现为

public boolean contains(double localX, double localY) {
    if (containsBounds(localX, localY)) {
        return (isPickOnBounds() || impl_computeContains(localX, localY));
    }
    return false;
}

impl_computeContains 定义在父类中,它是 Group 的超类

protected boolean impl_computeContains(double localX, double localY) {
    final Point2D tempPt = TempState.getInstance().point;
    for (int i=0, max=children.size(); i<max; i++) {
        final Node node = children.get(i);
        tempPt.x = (float)localX;
        tempPt.y = (float)localY;
        try {
            node.parentToLocal(tempPt);
        } catch (NoninvertibleTransformException e) {
            continue;
        }
        if (node.contains(tempPt.x, tempPt.y)) {
            return true;
        }
    }
    return false;
}

【讨论】:

  • 嗯,我没有看到在您的测试用例中您为组本身设置了一个侦听器?你只是没有包括那一点吗?无论如何感谢您的测试。但是,只需为组的矩形设置一个侦听器,我就得到了我想要的行为。我的节点基本上是矩形。我不知道我在做什么令人费解的事情,如果它真的应该开箱即用。
  • @user2499946,可以在构造函数中添加setOnMouseEntered(e -&gt; System.out.println("Entered group"));这一行。即使在组上设置了侦听器,您也不会收到该组的事件。
猜你喜欢
  • 2013-11-24
  • 2017-03-25
  • 1970-01-01
  • 2019-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-04
  • 1970-01-01
相关资源
最近更新 更多