When adding a second item to my stackpane, the first item loses its Event/MouseOn. Why? How can I fix? JavaFX

情到浓时终转凉″ 提交于 2019-12-05 11:33:44

StackPane orders items in Z-order: latter above the former. So, your second item gots all mouse clicks and first one (being covered by second) doesn't get anything.

For layout you've described you can use BorderPane:

public void start(Stage stage) throws Exception {
    BorderPane root = new BorderPane();
    root.setCenter(new Rectangle(100,100, Color.RED));
    root.setLeft(new Rectangle(10,10, Color.BLUE));
    root.setRight(new Rectangle(10,10, Color.CYAN));

    stage.setScene(new Scene(root,300,300));

    stage.show();
}
yaraju

You can make any Pane "mouse transparent", so that it doesn't consume any click events, and lets them pass through to the stack under it.

Here's some example code... this example sets up 4 panes in a stack, with just the mainPane accepting clicks to begin with.

StackPane rootPane = new StackPane();
VBox mainPane = new VBox(80);

BorderPane helpOverlayPane = new BorderPane();
helpOverlayPane.setMouseTransparent(true);

Canvas fullScreenOverlayCanvas = new Canvas();
fullScreenOverlayCanvas.setMouseTransparent(true);

VBox debugPane = new VBox();
debugPane.setAlignment(Pos.BASELINE_RIGHT);
AnchorPane debugOverlay = new AnchorPane();
debugOverlay.setMouseTransparent(true);
debugOverlay.getChildren().add(debugPane);
AnchorPane.setBottomAnchor(debugPane, 80.0);
AnchorPane.setRightAnchor(debugPane, 20.0);

rootPane.getChildren().addAll(mainPane, fullScreenOverlayCanvas, debugOverlay, helpOverlayPane);

Now, when you want to use your canvas to draw on top, make sure you change mouse transparent to false for just that stack, and keep all panes on top of it mouse transparent.

fullScreenOverlayCanvas.setMouseTransparent(false);
debugOverlay.setMouseTransparent(true);
fullScreenOverlayCanvas.setVisible(true);

doSomethingWithCanvasThatNeedsMouseClicks();

P.S. I did some editing of the code I had, so it may not run as-is. Also, see discussion of making only parts of panes transparent here: JavaFX Pass MouseEvents through Transparent Node to Children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!