JavaFX MouseEvent move rectangle

Description

JavaFX MouseEvent move rectangle


import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.shape.Rectangle;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class Main extends Application {
   @Override//from   w w  w . j a v  a2s  .c om
   public void start(Stage primaryStage) {
      // Create a pane
      Pane pane = new Pane();

      // Create a rectangle
      Rectangle rectangle = new Rectangle(5, 5, 30, 20);
      pane.getChildren().add(rectangle);

      // Create and register the handle
      pane.setOnMouseDragged(e -> {
         if (rectangle.contains(e.getX(), e.getY())) {
            pane.getChildren().clear();
            rectangle.setX(e.getX() - rectangle.getWidth() * .5);
            rectangle.setY(e.getY() - rectangle.getHeight() * .5);
            pane.getChildren().add(rectangle);
         }
      });

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



PreviousNext

Related