Search code examples
javafxmouseeventjava-8mousemouselistener

How to write a MouseListener for JavaFX


I want to write a little game where I shoot from an object to a specific direction on a JavaFX Panel using my mouse position.

I want to turn a Line in the direction where my Mouse is.

Line line = new Line(startPosX, startPosY, mouseDirectionX, mouseDirectionY);

How can I do that?


Solution

  • Add a MOUSE_MOVED event filter like this:

    public class Main extends Application {
    
        @Override
        public void start(Stage primaryStage) {
            try {
                Pane root = new Pane();
                Line line = new Line( 400,200,400,200);
                root.addEventFilter(MouseEvent.MOUSE_MOVED, e -> {
                    line.setEndX(e.getSceneX());
                    line.setEndY(e.getSceneY());
                });
                root.getChildren().add(line);
                Scene scene = new Scene(root, 800, 400);
                primaryStage.setScene(scene);
                primaryStage.show();
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    If you want the line to be limited in length, you'll have to do the proper calculations of course via the angle.