3

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();
}
}
asked May 9, 2015 at 12:28

3 Answers 3

2

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); 
}
});
Lrrr
4,8055 gold badges44 silver badges65 bronze badges
answered May 9, 2015 at 12:32
Sign up to request clarification or add additional context in comments.

Comments

0

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.
 }
 });
answered May 9, 2015 at 12:32

Comments

0

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 ;
}
answered May 9, 2015 at 12:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.