在拖放过程中,在鼠标图标旁边显示节点的半透明“副本”的最佳方式是什么?JavaFX拖放鼠标图标旁边的自定义节点
基本上我有一些带有彩色背景和文本标签的HBox,并且我想给出它们在被拖动时“粘”到鼠标光标的外观。
如果用户可以直观地验证他们正在拖动的内容,而不是仅仅将鼠标光标更改为各种拖动图标,那很好。场景生成器往往会在拖动某些组件(如RadioButton)时执行此操作。
在拖放过程中,在鼠标图标旁边显示节点的半透明“副本”的最佳方式是什么?JavaFX拖放鼠标图标旁边的自定义节点
基本上我有一些带有彩色背景和文本标签的HBox,并且我想给出它们在被拖动时“粘”到鼠标光标的外观。
如果用户可以直观地验证他们正在拖动的内容,而不是仅仅将鼠标光标更改为各种拖动图标,那很好。场景生成器往往会在拖动某些组件(如RadioButton)时执行此操作。
节点的“半透明”副本通过在节点上调用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();
}
}
呵呵,不知道你可以传递(空,空)到快照,因为我没有足够的RTFM ......嗯,这个工作无论如何。 – User
你在做“平台支持的拖放”(即你在某个节点上调用'startDragAndDrop')吗?如果是这样,你可以调用'Dragboard.setDragView(...)'来设置拖动的图像光标。 –
只是内部的,应用程序窗口之外没有任何东西。 – User
这不是我问的。 –