2

I have the following problem in my ScalaFX Application. I have a Label in a VBox. Both have a onMouseClicked listener assigned, as can be seen in my example code. When clicking on the inside label, both handlers are executed. This is not the behavior I want to force. I only want the labels listener to be executed.

Example-Code

new VBox{
  content add new Label {
    text = "inside label"
    onMouseClicked = (me : MouseEvent) => println("Execute just me!")
  }
  onMouseClicked = (me : MouseEvent) => println("Do not execute when label is clicked!")
}

Is there an easy way to stop the VBox handler from being executed when clicking the Label?

smoes
  • 591
  • 2
  • 17

1 Answers1

3

You need to consume the event. The following code works in JavaFX:

class TestPane extends Pane {

    private Label label;
    private VBox vbox;

    public TestPane() {
        label = new Label();
        label.setText("Waiting...");
        vbox = new VBox();
        vbox.getChildren().add(label);
        getChildren().add(vbox);
        label.setOnMouseClicked(new EventHandler<Event>() {
            @Override
            public void handle(Event event) {
                System.out.println("label event");
                event.consume();
            }
        });
        vbox.setOnMouseClicked(new EventHandler<Event>() {
            @Override
            public void handle(Event event) {
                System.out.println("vbox event");
            }
        });
    }
}

The event handling chain is well defined:

enter image description here

There's more information about how to manipulate the dispatching and handling of events on this page: Oracle Tutorial: Handling JavaFX Events

DaveB
  • 1,836
  • 1
  • 15
  • 13
  • That is quite a nice overview and supports my understanding of what my mouse click triggers. Consuming works fine and is what I searched for. Thank you! – smoes Nov 02 '14 at 18:42