Using JavaFX with drag and drop, is it possible to have a ghost of the dragged object follow the cursor?

喜欢而已 提交于 2019-12-10 10:34:49

问题


I have been looking for examples of Drag and Drop with Java but they always use a generic mouse cursor with a box attached to indicate an item is being dragged, whereas many tools (even browsers like Firefox) instead attach a ghost of the dragged object to the cursor to indicate what is being dragged. Can this be done in JavaFX?


回答1:


Yes you can set a drag view (arbitrary image) for a drag and drop operation.




回答2:


You can use DragBoard.setDragView(...); to set an image that is displayed during dragging.

Example code:

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


来源:https://stackoverflow.com/questions/29711190/using-javafx-with-drag-and-drop-is-it-possible-to-have-a-ghost-of-the-dragged-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!