VBox 的拖放功能

Drag and drop functionality with VBox

我正在尝试为我的 JavaFX 项目添加拖放功能。它有点工作,但不是真正在同一时间

VBox questions = new VBox();
questions.getChildren().add(createQustionType("long answer"));
questions.setStyle("-fx-border-color: blue;");
root.setCenter(questions);
questions.setOnDragOver(event ->
{
    event.acceptTransferModes(TransferMode.MOVE);
});
questions.setOnDragDropped(event ->
{
    event.setDropCompleted(true);
    questions.getChildren().add(createQustionType("long answer"));
    event.consume();
});

questions.setOnDragDone(event -> {});
VBox sidePanel = new VBox();
root.setLeft(sidePanel);
//other unnecessary code removed for question

String[] types = new String[]{"multiple choice", "long answer", "short answer"};
for (String type : types)
{
    Button btn = new Button(type);
    btn.setOnDragDetected(event ->
    {
        currBtn = (Button) event.getSource();
        event.consume();
    });
    sidePanel.getChildren().add(btn);}

createQuestionType 方法returns 一个边框并接受一个字符串参数

这是我目前所拥有的,我不知道我哪里出错了,因为当我从我的桌面或文档等拖动文件时它似乎可以工作,而我不希望它这样做。我想使用我添加到侧面板的按钮,因为这就是它的用途。

此外,我一直试图在拖动时更改光标,但也失败了。如果有人能告诉我我做错了什么,那就太好了。

对于那些不太理解我的问题的人,我深表歉意。下次我会尝试更好地表达我的问题。无论如何,我已经设法解决了我的问题。我意识到我必须使用 DragBoard and the ClipboardContent 这是我想出的最终代码

VBox questions = new VBox();
root.setCenter(questions);
questions.setOnDragOver(event ->
{
    if (event.getGestureSource() == currBtn && event.getDragboard().hasString())
    {
        event.acceptTransferModes(TransferMode.MOVE);
    }
    event.consume();
});
questions.setOnDragDropped(event ->
{
    Dragboard db = event.getDragboard();
    boolean success = false;
    if (db.hasString())
    {
        questions.getChildren().add(createQustionType(db.getString()));
        success = true;
    }
    event.setDropCompleted(success);
    event.consume();
});

questions.setOnDragDone(event ->
{
    System.out.println("Add clean up code");
    if (event.getTransferMode() == TransferMode.MOVE)
    {
        System.out.println("Drag Done");
    }
    event.consume();
});

VBox sidePanel = new VBox();
root.setLeft(sidePanel);
sidePanel.setMinWidth(100);
//sidePanel.setStyle("-fx-background-color: red");
sidePanel.setStyle("-fx-border-color: red; -fx-min-width: 100px;");
sidePanel.setSpacing(10);

String[] types = new String[]{"multiple choice", "long answer", "short answer"};
for (String type : types)
{
    Button btn = new Button(type);
    btn.getStyleClass().add("qBtn");
    btn.setStyle("-fx-border-color: black;");
    btn.setOnDragDetected(event ->
    {
        currBtn = (Button) event.getSource();
        System.out.println("Dragging node");
        Dragboard db = btn.startDragAndDrop(TransferMode.ANY);
        ClipboardContent content = new ClipboardContent();
        content.putString(btn.getText());
        db.setContent(content);

        event.consume();
    });
    sidePanel.getChildren().add(btn);
}