Delibz
Delibz

Reputation: 97

Javafx, how to detect mouse position?

I create a blue rectangle using JavaFX.

Can I change the color of the rectangle to red when the mouse moves into the area covered by the blue rectangle, and back to blue when the mouse moves out of the rectangle?

The rectangle I created:

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();
}
}

Upvotes: 3

Views: 3269

Answers (3)

James_D
James_D

Reputation: 209340

As well as the mouse-event based solutions described in other answers, you can also do this with CSS. Create the Rectangle without specifying a fill, and add a style class to it. (Note that the Builder class you are using is deprecated.) Add a 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:

rectangle-hover.css:

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

Upvotes: 0

shawwy
shawwy

Reputation: 122

I would suggest reading a bit about MouseEvents in JavaFX.

As for 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); 
}
});

Upvotes: 2

akhil_mittal
akhil_mittal

Reputation: 24157

You can add a mouse event handler to the appropriate JavaFX component in which 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.
      }
    });

Upvotes: 0

Related Questions