我做了一个简单的测试应用,组没有得到鼠标事件:
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;
}