I have a situation where I have a node container (HBox) and two child nodes in JavaFX. When I drag the left child nodes to the right, I get a lot of events to drag the left node, and finally, when I unlock the mouse over the right node, I get the click event on the parent. Below is the code to replicate this situation.
I want to know: how to stop the parent receiving this click event? I tried all kinds of event filters and event handlers on the left and right nodes that consume events, but I just canβt find the right ones (s) to prevent the click event being sent to the parent. Any ideas?
package test; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.stage.Stage; public class TestDrag extends Application { @Override public void start(Stage primaryStage) throws Exception { String leftHead = "Start dragging from me\n"; String dragStarted = "Drag begun; staying simple\n"; Label left = new Label(leftHead); left.setOnDragDetected(e -> { left.setText(leftHead + dragStarted); e.consume(); }); left.setOnMouseDragged(e -> { left.setText(leftHead + dragStarted + "Mouse dragged to: " + e.getSceneX() + ", " + e.getSceneY()); e.consume(); }); left.setOnMouseReleased(e -> { left.setText(leftHead + "Mouse released\n"); e.consume(); }); String rightHead = "Drag on to me\n"; Label right = new Label(rightHead); right.setOnMouseClicked(e -> { right.setText(rightHead + "Clicked me!\n"); }); left.setPrefSize(400, 300); left.setBackground(new Background(new BackgroundFill(Color.LIGHTBLUE, null, null))); right.setPrefSize(400, 300); right.setBackground(new Background(new BackgroundFill(Color.LIGHTPINK, null, null))); HBox hbox = new HBox(left, right); hbox.setOnMouseClicked(e -> { right.setText(rightHead + "Clicked the underlying HBox at " + System.currentTimeMillis() + "\n"); }); primaryStage.setScene(new Scene(hbox)); primaryStage.show(); } }
javafx javafx-8
Neil brown
source share