JavaFX MouseEvent inside Polygon

Description

JavaFX MouseEvent inside Polygon


import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.shape.Polygon;
import javafx.scene.paint.Color;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class Main extends Application {
   @Override// www. j ava 2s  .  com
   public void start(Stage primaryStage) {
      // Create a pane
      Pane pane = new Pane();

      // Create a polygon and set it properties
      Polygon polygon = new Polygon();
      pane.getChildren().add(polygon);
      ObservableList<Double> list = polygon.getPoints();
      list.addAll(40.0, 20.0, 70.0, 40.0, 60.0, 80.0, 45.0, 45.0, 20.0, 60.0
            , 100.0, 160.0);
      polygon.setFill(Color.WHITE);
      polygon.setStroke(Color.BLACK);

      // Create and register the handle
      pane.setOnMouseMoved(e -> {
         pane.getChildren().clear();
         Text text = new Text(e.getX(), e.getY(), "Mouse point is " +
            (polygon.contains(e.getX(), e.getY()) ? "inside " : "outside ") +
            "the polygon");
         pane.getChildren().addAll(polygon, text);
      });

      // Create a scene and place it in the stage
      Scene scene = new Scene(pane, 300, 150);
      primaryStage.setTitle("java2s.com");
      primaryStage.setScene(scene);
      primaryStage.show();
   }
}



PreviousNext

Related