Search code examples
javaeclipsejavafxscenebuildereclipse-photon

Scenebuilder/JavaFX polygons mouse event onClick


Link to scenebuilder and some Java code: https://i.sstatic.net/yBVJQ.jpg

Essentially, navigating and pictures will change based on where the person is going/facing.

I have polygons as D-pad arrows and I want to be able to detect when a person clicks on them. The "up" arrow polygon ID is "forward"
I read that forward.onMouseClickedProperty.addListener() or something can be used, but when I looked up "javafx polygon mouse event" I don't get how to implement into my project.

Can anyone tell me how to set up forward.onMouseClickedProperty.addListener()? Thanks!


Solution

  • 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!"));
        }
    }