javafx拖动形状

xxe27gdn  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(535)

我目前正在创建一个益智游戏。其思想是在左侧有一个滚动窗格,其中包含所有拼图块(javafx.shapes)。
我有一个代码,允许我拖动周围的片段,但如果我想把它拖到底部的滚动窗格,它飞回其初始位置。我希望形状可以从滚动窗格的顶部拖动到底部。

控制器:

  1. public class SpielModus extends Application{
  2. @FXML
  3. private ScrollPane pieceAreaScrollable;
  4. @FXML
  5. private Pane pieceArea;
  6. public static void main(String[] args) {
  7. launch(args);
  8. }
  9. @Override
  10. public void start(Stage primaryStage) throws Exception {
  11. this.stage = primaryStage;
  12. show();
  13. }
  14. @FXML
  15. public void initialize() {
  16. Circle circle = new Circle(50, 50, 50);
  17. Circle circle2 = new Circle(50, 200, 50);
  18. Group group = new Group(circle, circle2);
  19. // So that the Pane is bigger then ScrollPane to become Scrollable
  20. pieceArea.setMinHeight(2000);
  21. pieceArea.getChildren().addAll(group);
  22. group.setOnMouseDragged(e -> {
  23. group.setLayoutX(e.getSceneX());
  24. group.setLayoutY(e.getSceneY());
  25. });
  26. }
  27. public void show() {
  28. try {
  29. FXMLLoader loader = new FXMLLoader(getClass().getResource("SpielModus.fxml"));
  30. loader.setController(this);
  31. Parent layout = loader.load();
  32. stage.setScene(new Scene(layout));
  33. stage.show();
  34. } catch (IOException e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. }

fxml地址:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <?import javafx.scene.control.Label?>
  3. <?import javafx.scene.control.ScrollPane?>
  4. <?import javafx.scene.layout.ColumnConstraints?>
  5. <?import javafx.scene.layout.GridPane?>
  6. <?import javafx.scene.layout.Pane?>
  7. <?import javafx.scene.layout.RowConstraints?>
  8. <GridPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="720.0" prefWidth="1080.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.171">
  9. <columnConstraints>
  10. <ColumnConstraints minWidth="10.0" prefWidth="250.0" />
  11. <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
  12. </columnConstraints>
  13. <rowConstraints>
  14. <RowConstraints minHeight="10.0" prefHeight="30.0" />
  15. <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
  16. </rowConstraints>
  17. <children>
  18. <ScrollPane fx:id="pieceAreaScrollable" hbarPolicy="NEVER" prefHeight="200.0" prefWidth="200.0" vbarPolicy="ALWAYS" GridPane.rowSpan="2">
  19. <content>
  20. <Pane fx:id="pieceArea" prefHeight="200.0" prefWidth="200.0" />
  21. </content>
  22. </ScrollPane>
  23. </children>
  24. </GridPane>
unftdfkk

unftdfkk1#

您正在重新定位大窗格中的圆 pieceArea 基于相对于场景的鼠标坐标的位置。如果 pieceArea 已滚动,这将给出不正确的位置(因为它不考虑滚动)。你需要鼠标坐标相对于 pieceArea (公司的母公司) group ,这是发生鼠标拖动事件的节点)。
你可以这样做

  1. group.setOnMouseDragged(e -> {
  2. Point2D newLocation = group.localToParent(new Point2D(e.getX(), e.getY()));
  3. group.setLayoutX(newLocation.getX());
  4. group.setLayoutY(newLocation.getY());
  5. });

相关问题