Guest User

Untitled

a guest
Nov 18th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. import javafx.application.Application;
  2. import javafx.geometry.Point2D;
  3. import javafx.scene.Scene;
  4. import javafx.scene.input.MouseEvent;
  5. import javafx.scene.layout.Background;
  6. import javafx.scene.layout.BackgroundFill;
  7. import javafx.scene.layout.Pane;
  8. import javafx.scene.layout.StackPane;
  9. import javafx.scene.paint.Color;
  10. import javafx.scene.shape.Rectangle;
  11. import javafx.stage.Stage;
  12.  
  13. public class Main extends Application {
  14.  
  15. @Override
  16. public void start(Stage primaryStage) {
  17. Pane pane = new Pane();
  18. pane.setBackground(new Background(new BackgroundFill(Color.BLACK, null, null)));
  19. pane.setMaxSize(500, 300);
  20.  
  21. Rectangle rect = new Rectangle(100, 100, Color.FIREBRICK);
  22. rect.setOnMousePressed(this::handleMousePressed);
  23. rect.setOnMouseDragged(this::handleMouseDragged);
  24. pane.getChildren().add(rect);
  25.  
  26. StackPane root = new StackPane(pane);
  27.  
  28. primaryStage.setScene(new Scene(root, 600, 400));
  29. primaryStage.show();
  30. }
  31.  
  32. private Point2D origin;
  33.  
  34. private void handleMousePressed(MouseEvent event) {
  35. origin = new Point2D(event.getX(), event.getY());
  36. event.consume();
  37. }
  38.  
  39. private void handleMouseDragged(MouseEvent event) {
  40. Rectangle rect = (Rectangle) event.getSource();
  41. rect.setTranslateX(rect.getTranslateX() + event.getX() - origin.getX());
  42. rect.setTranslateY(rect.getTranslateY() + event.getY() - origin.getY());
  43. event.consume();
  44. }
  45.  
  46. }
Add Comment
Please, Sign In to add comment