Kutam Kutam -4 years ago 137
Java Question

Coordinate location of cursor and colour change with certain condition - JavaFX

Im starting to learn JavaFX. I have made a simple program that creates shapes.

I want to do basic events driven execution method, such as:


  1. print the coordinate of the cursor if its inside a shape

  2. changing the colour everytime the cursor enters a shape, then changing it back to the original once it is out of the shape



the following is what I have done

import javafx.application.Application;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.Group;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Polygon;


public class ColouredShapes extends Application {

@Override
public void start(Stage stage) {
int radius = 40;
int strokeWidth = 3;
Color strokeColor = Color.BROWN;

Circle circle1 = new Circle(250, 125, radius, Color.RED);
circle1.setStroke(strokeColor);
circle1.setStrokeWidth(strokeWidth);

Rectangle square = new Rectangle(375, 85, 80, 80);
square.setFill(Color.BLUE);
square.setStroke(strokeColor);
square.setStrokeWidth(strokeWidth);

Polygon polygon = new Polygon();
polygon.getPoints().addAll(new Double[]{
50.0, 85.0,
110.0, 60.0, 125.0, 175.0});

polygon.setFill(Color.YELLOWGREEN);

Group root = new Group();
root.getChildren().addAll(circle1, square, polygon);
Scene scene = new Scene(root, 500, 250, Color.LIGHTYELLOW);
stage.setScene(scene);
stage.show();

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

Answer Source

Add event mouse entered, exited, and moved handlers to the shape

square.setOnMouseMoved(new EventHandler<MouseEvent>() {

  @Override
  public void handle(final MouseEvent event) {
    if (square.contains(new Point2D(event.getSceneX(), event.getSceneY()))) {
      System.out.println(event.getScreenX());
      System.out.println(event.getScreenY());
    }

  }
});
square.setOnMouseEntered(new EventHandler<MouseEvent>() {

  @Override
  public void handle(final MouseEvent event) {
    square.setFill(Color.GREEN);
  }
});
square.setOnMouseExited(new EventHandler<MouseEvent>() {

  @Override
  public void handle(final MouseEvent event) {
    square.setFill(null);

  }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download