You can use stackPane.setPickOnBounds(false); . This means that the stack panel will only be identified as the target of the mouse action if the point it was clicked was not transparent (instead of the default behavior, which should identify it as the target of the mouse action if the mouse click is within its borders) .
Here is the SSCCE:
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class ClickThroughStackPane extends Application { @Override public void start(Stage primaryStage) { Canvas canvas = new Canvas(400,400); canvas.setOnMouseClicked(e -> System.out.println("Mouse click: canvas")); HBox statusBar = new HBox(new Label("Status")); statusBar.setOnMouseClicked(e -> System.out.println("Mouse click: statusBar")); BorderPane borderPane = new BorderPane(canvas, statusBar, null, null, null); Button button = new Button("Click"); button.setOnAction(e -> System.out.println("Button pressed")); StackPane stack = new StackPane(button); stack.setPickOnBounds(false); StackPane root = new StackPane(borderPane, stack); primaryStage.setScene(new Scene(root)); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
Note that the top panel of the stack seems unnecessary, as you can simply add the user interface elements that it contains directly to the stack panel. The previous example can simply be rewritten:
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class ClickThroughStackPane extends Application { @Override public void start(Stage primaryStage) { Canvas canvas = new Canvas(400,400); canvas.setOnMouseClicked(e -> System.out.println("Mouse click: canvas")); HBox statusBar = new HBox(new Label("Status")); statusBar.setOnMouseClicked(e -> System.out.println("Mouse click: statusBar")); BorderPane borderPane = new BorderPane(canvas, statusBar, null, null, null); Button button = new Button("Click"); button.setOnAction(e -> System.out.println("Button pressed")); StackPane root = new StackPane(borderPane, button); primaryStage.setScene(new Scene(root)); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
source share