是否可以将 .hoverProperty().addListener 添加到 HBox 的所有子项(在我的情况下为按钮)?我知道我可以为每个按钮分配单独的侦听器。但是我很感兴趣是否可以一次为所有孩子分配一个听众。HBox 的按钮之间有 15 px 的间距。
问问题
2182 次
1 回答
3
只需将侦听器添加到 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文档,您现在也可以使用鼠标侦听器:
注意,当前hover的实现依赖于鼠标进入和退出事件来判断这个Node是否处于悬停状态;这意味着此功能目前仅在具有鼠标的系统上受支持。未来的实现可能会提供支持悬停的替代方法。
于 2015-03-02T16:04:27.610 回答