JavaFX拖放删除鼠标图标旁边的自定义节点

时间:2017-01-18 23:40:00

标签: java javafx javafx-8

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

基本上我的HBox有彩色背景和文字标签,我想在拖动时给它们“粘”在鼠标光标上。

如果用户可以直观地验证他们拖动的内容,而不是仅仅看到鼠标光标变为各种拖动图标,那就太好了。拖动某些组件(如RadioButton。

)时,Scene Builder会执行此操作

1 个答案:

答案 0 :(得分:2)

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

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();
    }
}