我有一些顶部装饰窗格,我想处理/预处理鼠标事件,但不应该消耗它们,即所有重叠的窗格都应该像装饰窗格没有重叠一样工作。
这个怎么做?我几次尝试都失败了。
下面是带有 3 个窗格的代码。绿色一是“装饰”。任务是使其对鼠标事件透明。黄色和蓝色窗格是工作窗格。它们应该像没有被绿色窗格重叠一样工作。
但是绿色窗格仍然应该接收鼠标事件。
注释行表示我尝试的内容,注释说明出现的错误:
import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
/**
* Created by dims on 13.10.2016.
*/
public class DelegateEventsToOverlappedNodes extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
StackPane root = new StackPane();
root.setBackground(new Background(new BackgroundFill(Color.RED, CornerRadii.EMPTY, Insets.EMPTY)));
AnchorPane yellowPane = new AnchorPane();
yellowPane.setBackground(new Background(new BackgroundFill(Color.YELLOW, CornerRadii.EMPTY, Insets.EMPTY)));
yellowPane.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println("yellowPane clicked");
}
});
root.getChildren().add(yellowPane);
Pane bluePane = new Pane();
bluePane.setBackground(new Background(new BackgroundFill(Color.BLUE, CornerRadii.EMPTY, Insets.EMPTY)));
bluePane.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println("bluePane clicked");
}
});
AnchorPane.setLeftAnchor(bluePane, 200.);
AnchorPane.setRightAnchor(bluePane, 200.);
AnchorPane.setTopAnchor(bluePane, 200.);
AnchorPane.setBottomAnchor(bluePane, 200.);
yellowPane.getChildren().add(bluePane);
AnchorPane greenPane = new AnchorPane();
greenPane.setBackground(new Background(new BackgroundFill(Color.rgb(0, 255, 0, 0.9), CornerRadii.EMPTY, Insets.EMPTY)));
greenPane.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println("greenPane clicked");
}
});
// greenPane.setVisible(false); // green pane invisible at all
// greenPane.setMouseTransparent(true); // green clicked doesn't occur
// greenPane.addEventHandler(Event.ANY, event -> yellowPane.fireEvent(event)); // works for yellow pane, but not for blue sub pane
root.getChildren().add(greenPane);
Scene scene = new Scene(root, 800, 600);
primaryStage.setScene(scene);
primaryStage.setTitle("DelegateEventsToOverlappedNodes");
primaryStage.show();
}
public static void main(String[] args) {
DelegateEventsToOverlappedNodes.launch(args);
}
}