java - 在 Javafx 中拖动按钮

标签 java drag-and-drop javafx draggable drag

我有一个按钮,我想拖动它并在一段时间后将其放下。 我在网上搜索了我遇到的最有用的东西是this关联。 与提供的链接类似,我希望将按钮拖动到光标所在的任何位置,只有当鼠标按钮向上时,按钮才应该放下。 这个问题如何解决?提前致谢

最佳答案

我设法制作了一个 borderPane 并在其上放置了一个按钮。当您释放鼠标时,按钮会被拖动并释放!

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class ButtonDraggable extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        BorderPane borderPane = new BorderPane();
        borderPane.setPrefSize(800, 600);
        final Button button = new Button("Drag ME !");

        final Delta dragDelta = new Delta();
        button.setOnMousePressed(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                // record a delta distance for the drag and drop operation.
                dragDelta.x = button.getLayoutX() - mouseEvent.getSceneX();
                dragDelta.y = button.getLayoutY() - mouseEvent.getSceneY();
                button.setCursor(Cursor.MOVE);
            }
        });
        button.setOnMouseReleased(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                button.setCursor(Cursor.HAND);
            }
        });
        button.setOnMouseDragged(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                button.setLayoutX(mouseEvent.getSceneX() + dragDelta.x);
                button.setLayoutY(mouseEvent.getSceneY() + dragDelta.y);
            }
        });
        button.setOnMouseEntered(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                button.setCursor(Cursor.HAND);
            }
        });

        borderPane.setCenter(button);

        Scene scene = new Scene(borderPane);

        stage.setScene(scene);
        stage.show();

    }

    // records relative x and y co-ordinates.
    class Delta {
        double x, y;
    }

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

}

如有任何疑问,请随时发表评论!

-AA

关于java - 在 Javafx 中拖动按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22139615/

相关文章:

java - 使用 System.currentTimeMillis() 同步计时器计划

来自用户输入的 Java 对象名称作为方法调用

java - 如何对一条线进行动画着色,就像 JavaFX 中通过的信号一样

java - Android:拖放多个图像

javascript - Dojo DND 的 UI 与显示项目时的 UI 不同

java - 在上下文菜单项上单击 Javafx 显示弹出窗口

canvas - Java Fx setOnMouseDragged 变慢

java - 在 Ubuntu 上运行 JavaFX .jar 文件时出错

java - 在没有注释的情况下将 Hibernate 迁移到 JPA

android - 重新启动时保持拖放项目的位置