JavaFX中的按钮拖放

时间:2017-03-01 11:45:43

标签: drag-and-drop javafx-2

我正在尝试开发一个应用程序,用户可以从托盘中拖动按钮并将其拖放到画布上以创建工作流程。用户将按钮拖放到画布后,他应该能够双击按钮打开表单以更新详细信息并保存。

我需要的帮助是实现拖放部分。任何人都可以帮我吗

谢谢!

1 个答案:

答案 0 :(得分:1)

以下是我实施拖放按钮和双击事件的方法

double orgSceneX, orgSceneY;
double orgTranslateX, orgTranslateY;
int i = 1;

@Override
public void start(Stage primaryStage) {
    try {

        BorderPane root = new BorderPane();

        Label label = new Label();

        Button button = new Button("Hello");
        button.setOnMousePressed(buttonMousePressedEventHandler);
        button.setOnMouseDragged(buttonOnMouseDraggedEventHandler);
        button.setCursor(Cursor.CROSSHAIR);

        button.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
                    if (mouseEvent.getClickCount() == 2) {
                        label.setText("Double Click Fire... " + i);
                        i = i + 1;
                    }
                }
            }
        });

        HBox box = new HBox();
        box.setSpacing(15);
        box.getChildren().addAll(button);

        VBox box2 = new VBox();
        box2.setSpacing(50);
        box2.getChildren().addAll(label, box);

        root.setCenter(box2);

        Scene scene = new Scene(root, 400, 400);
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.show();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

EventHandler<MouseEvent> buttonMousePressedEventHandler = new EventHandler<MouseEvent>() {

    @Override
    public void handle(MouseEvent t) {
        orgSceneX = t.getSceneX();
        orgSceneY = t.getSceneY();
        orgTranslateX = ((Button) (t.getSource())).getTranslateX();
        orgTranslateY = ((Button) (t.getSource())).getTranslateY();

        ((Button) (t.getSource())).toFront();
    }
};

EventHandler<MouseEvent> buttonOnMouseDraggedEventHandler = new EventHandler<MouseEvent>() {

    @Override
    public void handle(MouseEvent t) {
        double offsetX = t.getSceneX() - orgSceneX;
        double offsetY = t.getSceneY() - orgSceneY;
        double newTranslateX = orgTranslateX + offsetX;
        double newTranslateY = orgTranslateY + offsetY;

        ((Button) (t.getSource())).setTranslateX(newTranslateX);
        ((Button) (t.getSource())).setTranslateY(newTranslateY);
    }
};

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