首页 > 解决方案 > Scenebuilder/JavaFX 多边形鼠标事件 onClick

问题描述

链接到 scenebuilder 和一些 Java 代码:https ://imgur.com/a/FOr1Mag

本质上,导航和图片将根据人的去向/面对的地方而改变。

我有多边形作为 D-pad 箭头,我希望能够检测到一个人何时点击它们。“向上”箭头多边形 ID 是“向前”
,我读到 forward.onMouseClickedProperty.addListener() 或其他可以使用的东西,但是当我查找“javafx 多边形鼠标事件”时,我不知道如何在我的项目中实现。

谁能告诉我如何设置 forward.onMouseClickedProperty.addListener()?谢谢!

标签: javaeclipsejavafxscenebuildereclipse-photon

解决方案


import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;

public class ClickablePolygonApp extends Application {

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

    @Override
    public void start(Stage stage) throws Exception {
        Polygon polygon = new Polygon();
        polygon.getPoints().addAll(new Double[] {
                0., 80.,
                80., 80.,
                40., 20.
        });

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

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

        polygon.setOnMouseClicked(mouseEvent -> System.out.println("1st way to handle Click!"));
        polygon.addEventHandler(MouseEvent.MOUSE_CLICKED, mouseEvent -> System.out.println("2nd way to handle click!"));
    }
}

推荐阅读