通过拖放使用JavaFX,是否可以使拖动对象的重影跟随光标?

Mar*_*een 2 java drag-and-drop javafx-8

我一直在寻找使用Java进行拖放的示例,但是他们总是使用附加框的通用鼠标光标来指示正在拖动项目,而许多工具(甚至像Firefox这样的浏览器)会将拖动对象的重影附加到光标指示正在拖动的内容.可以在JavaFX中完成吗?

Jam*_*s_D 6

您可以使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)