【发布时间】:2015-04-17 23:46:11
【问题描述】:
我一直在寻找使用 Java 进行拖放的示例,但它们总是使用带有框的通用鼠标光标来指示正在拖动的项目,而许多工具(甚至像 Firefox 之类的浏览器)却附加了一个幽灵拖动对象到光标以指示正在拖动的内容。这可以在 JavaFX 中完成吗?
【问题讨论】:
标签: java drag-and-drop javafx-8
我一直在寻找使用 Java 进行拖放的示例,但它们总是使用带有框的通用鼠标光标来指示正在拖动的项目,而许多工具(甚至像 Firefox 之类的浏览器)却附加了一个幽灵拖动对象到光标以指示正在拖动的内容。这可以在 JavaFX 中完成吗?
【问题讨论】:
标签: java drag-and-drop javafx-8
您可以使用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);
}
}
【讨论】:
是的,您可以set a drag view(任意图像)进行拖放操作。
【讨论】: