JavaFX 在鼠标图标旁边拖放自定义节点

标签 java javafx javafx-8

在拖放过程中,在鼠标图标旁边显示节点的半透明“副本”的最佳方式是什么?

基本上,我有带有彩色背景和文本标签的 HBox,我想让它们在被拖动时看起来“粘”在鼠标光标上。

如果用户能够直观地验证他们正在拖动的内容,而不是仅仅看到鼠标光标变为各种拖动图标,那就太好了。当您拖动某些组件(例如单选按钮)时,场景生成器往往会执行此操作。

最佳答案

“节点的半透明“复制””是通过在节点上调用 snapshot(null, null) 来完成的,该节点返回一个 WritableImage。然后将此WritableImage 设置为DragBoard 的拖动 View 。下面是一个关于如何执行此操作的小示例:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DataFormat;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class DragAndDrop extends Application {
    private static final DataFormat DRAGGABLE_HBOX_TYPE = new DataFormat("draggable-hbox");

    @Override
    public void start(Stage stage) {
        VBox content = new VBox(5);

        for (int i = 0; i < 10; i++) {
            Label label = new Label("Test drag");

            DraggableHBox box = new DraggableHBox();
            box.getChildren().add(label);

            content.getChildren().add(box);
        }

        stage.setScene(new Scene(content));
        stage.show();
    }

    class DraggableHBox extends HBox {
        public DraggableHBox() {
            this.setOnDragDetected(e -> {
                Dragboard db = this.startDragAndDrop(TransferMode.MOVE);

                // This is where the magic happens, you take a snapshot of the HBox.
                db.setDragView(this.snapshot(null, null));

                // The DragView wont be displayed unless we set the content of the dragboard as well. 
                // Here you probably want to do more meaningful stuff than adding an empty String to the content.
                ClipboardContent content = new ClipboardContent();
                content.put(DRAGGABLE_HBOX_TYPE, "");
                db.setContent(content);

                e.consume();
            });
        }
    }

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

关于JavaFX 在鼠标图标旁边拖放自定义节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41731382/

相关文章:

JavaFX 属性 : Overriding getBean() method?

css - 如何设置菜单按钮和菜单项的样式

java - ScrollPane 未按需显示,FlowPane 内容

java - 如何使用prepareStatement更新数据,字段和值都需要设置

java - 根据按钮 Action 动态从Mysql中检索信息

更改场景构建器和 jdk 后 javaFX 程序无法正常工作

performance - 计时 JavaFX Canvas 应用程序

java - 访问完整的字典java

java - java中如何通过反射获取注解

java - JPA + Hibernate + Spring + OneToMany 删除级联