Alyona
Alyona

Reputation: 1792

Children's hover listening with JavaFX

Is it possible to add .hoverProperty().addListener to all children(in my case buttons) of HBox? I know that I can assign separate listeners for each button. But I was interested if it is possible to assign one listener to all children at once. Buttons of HBox have 15 px spacing between them.

Upvotes: 1

Views: 2443

Answers (1)

Roland
Roland

Reputation: 18425

Just add the listener to the 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);
    }
}

According to the hoverProperty documentation you could as well use a mouse listener for now:

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.

Upvotes: 3

Related Questions