Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird behavior of two mouse events being triggered infinitely in tooltip code

I am trying to implement a custom tooltip using the javafx.stage.Popup. The sample demo code is:

public class PopupDemo extends Application {

    private Popup tooltip;
    private final SepiaTone sepiaTone = new SepiaTone();

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

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("PopupDemo");

        Label content = new Label();
        content.setStyle("-fx-background-color:#FCFBBD; -fx-padding: 5; -fx-border-color: #BFBD3B");

        tooltip = new Popup();
        tooltip.getContent().add(content);

        VBox vbox = new VBox(10);
        for (int i = 0; i < 5; i++) {
            final Label lbl = new Label("item " + i);
            lbl.setStyle("-fx-border-color:darkgray; -fx-background-color:lightgray");
            lbl.setMaxSize(80, 60);
            lbl.setMinSize(80, 60);
            lbl.setAlignment(Pos.CENTER);

            lbl.setOnMouseEntered(new EventHandler<MouseEvent>() {

                @Override
                public void handle(final MouseEvent e) {
                    lbl.setEffect(sepiaTone);
                    lbl.setStyle("-fx-cursor: hand");
                    Label content = (Label) tooltip.getContent().get(0);
                    content.setText(lbl.getText());
                    tooltip.show(lbl, e.getScreenX(), e.getScreenY());
                }
            });
            lbl.setOnMouseExited(new EventHandler<MouseEvent>() {

                @Override
                public void handle(MouseEvent e) {
                    lbl.setEffect(null);
                    lbl.setStyle("-fx-cursor: default");
                    tooltip.hide();
                }
            });

            vbox.getChildren().add(lbl);
        }

        StackPane root = new StackPane();
        root.setPadding(new Insets(20));
        root.getChildren().add(vbox);
        primaryStage.setScene(new Scene(root, 600, 400));
        primaryStage.show();
    }
}

When I move the mouse over the labels the popup shows up and it is working great. But in some cases the two mouse event handlers OnMouseEntered and OnMouseExited are being called continuously one after another. One can reproduce this by running provided example, maximising a window and hovering labels continuously.

Is there a way to avoid this? I'm using JavaFX 2.0.1. Thanks.

like image 576
Uluk Biy Avatar asked Feb 07 '12 14:02

Uluk Biy


1 Answers

It's a classic problem: you put mouse at a point, node receives MouseEntered — tooltip appears under the mouse and covers the node triggering MouseExited.

To avoid that you can change tooltip.show(lbl, e.getScreenX(), e.getScreenY()) call to

tooltip.show(lbl, e.getScreenX() + 1, e.getScreenY() + 1);
like image 68
Sergey Grinev Avatar answered Nov 14 '22 22:11

Sergey Grinev