javafx拖动形状

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

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

控制器:

public class SpielModus extends Application{
    @FXML
    private ScrollPane pieceAreaScrollable;

    @FXML
    private Pane pieceArea;

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        this.stage = primaryStage;
        show();
    }

    @FXML
    public void initialize() {
        Circle circle = new Circle(50, 50, 50);
        Circle circle2 = new Circle(50, 200, 50);

        Group group = new Group(circle, circle2);

        // So that the Pane is bigger then ScrollPane to become Scrollable
        pieceArea.setMinHeight(2000);
        pieceArea.getChildren().addAll(group);

        group.setOnMouseDragged(e -> {
            group.setLayoutX(e.getSceneX());
            group.setLayoutY(e.getSceneY());
        });
    }

    public void show() {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("SpielModus.fxml"));
            loader.setController(this);

            Parent layout = loader.load();
            stage.setScene(new Scene(layout));
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

fxml地址:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.RowConstraints?>

<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">
  <columnConstraints>
    <ColumnConstraints minWidth="10.0" prefWidth="250.0" />
    <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
  </columnConstraints>
  <rowConstraints>
    <RowConstraints minHeight="10.0" prefHeight="30.0" />
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
  </rowConstraints>
   <children>
      <ScrollPane fx:id="pieceAreaScrollable" hbarPolicy="NEVER" prefHeight="200.0" prefWidth="200.0" vbarPolicy="ALWAYS" GridPane.rowSpan="2">
         <content>
            <Pane fx:id="pieceArea" prefHeight="200.0" prefWidth="200.0" />
         </content>
      </ScrollPane>
   </children>
</GridPane>
unftdfkk

unftdfkk1#

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

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

相关问题