【问题标题】:Using JavaFX with drag and drop, is it possible to have a ghost of the dragged object follow the cursor?使用带有拖放功能的JavaFX,是否可以让拖动对象的幽灵跟随光标?
【发布时间】:2015-04-17 23:46:11
【问题描述】:

我一直在寻找使用 Java 进行拖放的示例,但它们总是使用带有框的通用鼠标光标来指示正在拖动的项目,而许多工具(甚至像 Firefox 之类的浏览器)却附加了一个幽灵拖动对象到光标以指示正在拖动的内容。这可以在 JavaFX 中完成吗?

【问题讨论】:

    标签: java drag-and-drop javafx-8


    【解决方案1】:

    您可以使用DragBoard.setDragView(...); 设置在拖动过程中显示的图像。

    示例代码:

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.control.TextField;
    import javafx.scene.input.ClipboardContent;
    import javafx.scene.input.Dragboard;
    import javafx.scene.input.TransferMode;
    import javafx.scene.layout.HBox;
    import javafx.scene.layout.StackPane;
    import javafx.scene.text.Text;
    import javafx.stage.Stage;
    
    public class DragViewExample extends Application {
    
        @Override
        public void start(Stage primaryStage) {
            TextField tf = new TextField("Drag from here");
            Label label = new Label("Drop here");
            tf.setOnDragDetected(e -> {
                Dragboard db = tf.startDragAndDrop(TransferMode.COPY);
                db.setDragView(new Text(tf.getText()).snapshot(null, null), e.getX(), e.getY());
                ClipboardContent cc = new ClipboardContent();
                cc.putString(tf.getText());
                db.setContent(cc);
            });
            label.setOnDragOver(e -> {
                e.acceptTransferModes(TransferMode.COPY);
            });
            label.setOnDragDropped(e -> {
                Dragboard db = e.getDragboard();
                if (db.hasString()) {
                    label.setText(db.getString());
                    e.setDropCompleted(true);
                } else {
                    e.setDropCompleted(false);
                }
            });
    
            Scene scene = new Scene(new StackPane(new HBox(10, tf, label)), 350, 75);
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    【讨论】:

    • 正如@jewelsea 指出的那样(对不起,交叉发布),参数可以是您喜欢的任何图像。
    【解决方案2】:

    是的,您可以set a drag view(任意图像)进行拖放操作。

    【讨论】:

      猜你喜欢
      • 2018-12-25
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多