JavaFx画布鼠标事件

时间:2018-12-05 09:25:28

标签: javafx

我只想在绘制形状的地方拦截画布上的鼠标事件,但是在其他所有透明区域中,我希望具有类似属性mouseTransparent true的行为。 我可以使用ImageView实现这一点,透明区域不会拦截鼠标事件。

public void start(Stage primaryStage) throws Exception {
    primaryStage.setTitle("Drawing Operations Test");
    Pane root = new Pane();
    root.setStyle("-fx-background-color: #C9E3AF");
    root.setMinSize(1000, 1000);
    root.setOnMouseClicked(event -> {
        System.out.println("Clicked on root pane");
    });

    Canvas canvas1 = new Canvas(512, 512);

    canvas1.getGraphicsContext2D().setFill(Color.BLACK);
    canvas1.getGraphicsContext2D().fillRect(250, 250, 250, 250);
    canvas1.setOnMouseClicked(event -> {
        System.out.println("Clicked on canvas1");
    });
    canvas1.setPickOnBounds(false);

    Canvas canvas2 = new Canvas(512, 512);

    canvas2.getGraphicsContext2D().setFill(Color.RED);
    canvas2.getGraphicsContext2D().fillRect(200, 200, 250, 250);
    canvas2.setOnMouseClicked(event -> {
        System.out.println("Clicked on canvas2");
    });
    canvas2.setPickOnBounds(false);


    SnapshotParameters param1 = new SnapshotParameters();

    param1.setFill(Color.TRANSPARENT);
    WritableImage image1 = canvas1.snapshot(param1, new WritableImage(512, 512));

    SnapshotParameters param2 = new SnapshotParameters();

    param2.setFill(Color.TRANSPARENT);
    WritableImage image2 = canvas2.snapshot(param2, new WritableImage(512, 512));

    ImageView view1 = new ImageView(image1);
    view1.setOnMouseClicked(event -> {
        System.out.println("Clicked on view1");
    });
    view1.setPickOnBounds(false);

    ImageView view2 = new ImageView(image2);
    view2.setOnMouseClicked(event -> {
        System.out.println("Clicked on view2");
    });
    view2.setPickOnBounds(false);

    // ImageView test
    // root.getChildren().addAll(view1, view2);

    // Canvas test
    root.getChildren().addAll(canvas1, canvas2);
    Scene sc = new Scene(root);

    primaryStage.setScene(sc);
    primaryStage.setX(0);
    primaryStage.setY(0);
    primaryStage.show();
}

使用Canvas还能做到吗?

1 个答案:

答案 0 :(得分:0)

就我而言,使用 Canvas 是不可能的,但是使用 Group Shape 可以为您提供所有画布的功能以及您期望的行为。

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

public class ShapesApp extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        Circle circle = new Circle(100);
        circle.setFill(Color.BLUE);

        Group group = new Group(circle);
        group.setOnMouseMoved(System.out::println);

        StackPane stackPane = new StackPane(group);
        stackPane.setPrefSize(400, 400);

        stage.setScene(new Scene(stackPane));
        stage.show();
    }
}