JavaFX点击覆盖堆栈窗格

时间:2016-11-18 13:11:58

标签: java user-interface input javafx java-8

schematic

正如您在上图中所看到的,我有一个包含两个元素的stackpane,一个BorderPane(它还包含一个画布和一个状态栏)和另一个stackpane(其中包含一些其他UI内容)。

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

你是怎么做到的?

1 个答案:

答案 0 :(得分:8)

您可以使用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);
    }
}