Javafx how to detect mouse position?

I am creating a blue rectangle using JavaFX.

Is it possible to change the color of the rectangle to red when the mouse moves to the area covered by the blue rectangle and back to blue when the mouse leaves the rectangle?

Created rectangle:

public class ColorfulRectangle extends Application {

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

    @Override
    public void start(Stage primaryStage) {
    Group root = new Group();
    Scene scene = new Scene(root, 400, 300, Color.WHITE);

    Rectangle rect1 = RectangleBuilder.create()
    .x(50)
    .y(50)
    .width(100)
    .height(100)
    .fill(Color.BLUE)
    .build();

    root.getChildren().add(rect1);
    primaryStage.setScene(scene);
    primaryStage.show();
}
}

      

+3


source to share


3 answers


I would suggest reading up on MouseEvents in JavaFX a bit .

Regarding your answer:



rect1.setOnMouseEntered(new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
    rect1.setFill(Color.RED); 
}
});

rect1.setOnMouseExited(new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
    rect1.setFill(Color.BLUE); 
}
});

      

+2


source


You can add a mouse event handler to the appropriate JavaFX component where you want to track the mouse location:



final Label myLabel = new Label("Mouse Location Monitor");
myLabel.setOnMouseEntered(new EventHandler<MouseEvent>() {
      @Override public void handle(MouseEvent event) {
        String msg = "(x: " + event.getX() + ", y: " + event.getY() + ")";
        // do anything now.
      }
    });

      

0


source


Apart from the mouse event based solutions described in other answers, you can also do this with CSS. Create Rectangle

without specifying a fill and add a style class to it. (Note that the class Builder

you are using is deprecated.) Add the stylesheet to the scene.

@Override
public void start(Stage primaryStage) {
    Group root = new Group();
    Scene scene = new Scene(root, 400, 300, Color.WHITE);

    scene.getStylesheets().add("rectangle-hover.css");

    Rectangle rect1 = new Rectangle(50, 50, 100, 100);
    rect1.getStyleClass().add("my-rectangle");

    root.getChildren().add(rect1);
    primaryStage.setScene(scene);
    primaryStage.show();
}

      

Then define the style in an external file:

hover.css rectangle:

.my-rectangle {
    -fx-fill: blue ;
}
.my-rectangle:hover {
    -fx-fill: red ;
}

      

0


source







All Articles