JavaFX 点击覆盖堆栈窗格

2022-09-04 03:20:21

schematic

正如您在上面的图中看到的,我有一个包含两个元素的堆栈窗格,一个是 BorderPane(再次包含画布和状态栏),另一个是堆栈窗格(包含一些其他 UI 内容)。

我希望能够从绿色堆栈窗格的不可见区域单击到黄色边框,但仍然允许单击绿色堆栈窗格中的实际UI内容(其中有可单击的东西,如按钮等)。

你是怎么做到的?


答案 1

您可以使用 .这意味着,仅当单击堆栈窗格的点不透明时,堆栈窗格才会被标识为鼠标操作的目标(而不是默认行为,即如果鼠标单击在其边界内,则将其标识为鼠标操作的目标)。stackPane.setPickOnBounds(false);

这是一个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);
    }
}

请注意,顶部堆栈窗格似乎没有必要,因为您只需将其包含的 UI 元素直接添加到基础堆栈窗格即可。前面的示例可以简单地重写:

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);
    }
}

答案 2

推荐