Children 使用 JavaFX 悬停监听
Children's hover listening with JavaFX
是否可以将 .hoverProperty().addListener 添加到 HBox 的所有 children(在我的例子中是按钮)?我知道我可以为每个按钮分配单独的监听器。但是我很感兴趣是否可以一次为所有 children 分配一个侦听器。 HBox 的按钮之间有 15 px 的间距。
只需将侦听器添加到 HBox:
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
Group root = new Group();
HBox hBox = new HBox();
hBox.setSpacing(30);
for (int i = 0; i < 10; i++) {
hBox.getChildren().add(new Button("Button " + i));
}
hBox.hoverProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
System.out.println("Hover: " + oldValue + " -> " + newValue);
}
});
hBox.addEventFilter(MouseEvent.MOUSE_ENTERED, e -> System.out.println( e));
hBox.addEventFilter(MouseEvent.MOUSE_EXITED, e -> System.out.println( e));
hBox.addEventFilter(MouseEvent.MOUSE_MOVED, e -> {
if( e.getTarget() instanceof Button) {
System.out.println( e);
}
});
hBox.setMaxHeight(100);
root.getChildren().add( hBox);
Scene scene = new Scene( root, 800, 500);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
根据 hoverProperty 文档,您现在也可以使用鼠标侦听器:
Note that current implementation of hover relies on mouse enter and
exit events to determine whether this Node is in the hover state; this
means that this feature is currently supported only on systems that
have a mouse. Future implementations may provide alternative means of
supporting hover.
是否可以将 .hoverProperty().addListener 添加到 HBox 的所有 children(在我的例子中是按钮)?我知道我可以为每个按钮分配单独的监听器。但是我很感兴趣是否可以一次为所有 children 分配一个侦听器。 HBox 的按钮之间有 15 px 的间距。
只需将侦听器添加到 HBox:
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
Group root = new Group();
HBox hBox = new HBox();
hBox.setSpacing(30);
for (int i = 0; i < 10; i++) {
hBox.getChildren().add(new Button("Button " + i));
}
hBox.hoverProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
System.out.println("Hover: " + oldValue + " -> " + newValue);
}
});
hBox.addEventFilter(MouseEvent.MOUSE_ENTERED, e -> System.out.println( e));
hBox.addEventFilter(MouseEvent.MOUSE_EXITED, e -> System.out.println( e));
hBox.addEventFilter(MouseEvent.MOUSE_MOVED, e -> {
if( e.getTarget() instanceof Button) {
System.out.println( e);
}
});
hBox.setMaxHeight(100);
root.getChildren().add( hBox);
Scene scene = new Scene( root, 800, 500);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
根据 hoverProperty 文档,您现在也可以使用鼠标侦听器:
Note that current implementation of hover relies on mouse enter and exit events to determine whether this Node is in the hover state; this means that this feature is currently supported only on systems that have a mouse. Future implementations may provide alternative means of supporting hover.