JavaFX在Gridpanes上拖放事件

时间:2015-08-14 09:06:07

标签: java drag-and-drop javafx-8 gridpane

我尝试在网格窗格中执行Drag& Drop-Event,但它没有用。检测到拖动但是拖动和放下事件都没有。我做错了什么?

这是我尝试过的代码:

public class FXMLDocumentController implements Initializable {

    @FXML
    private GridPane grid;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        StackPane sourcePane = new StackPane(new Text("Source"));    
        StackPane targetPane = new StackPane(new Text("Target"));        

        sourcePane.setOnDragDetected(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                sourcePane.startDragAndDrop(TransferMode.ANY);
                System.out.println("Drag detected");
                event.consume();
            }
        });


        targetPane.setOnDragOver(new EventHandler<DragEvent>() {
            @Override
            public void handle(DragEvent event) {
                event.acceptTransferModes(TransferMode.ANY);
                System.out.println("Drag over detected");
                event.consume();
            }
        });

        targetPane.setOnDragDropped(new EventHandler<DragEvent>() {
            @Override
            public void handle(DragEvent event) {
                event.acceptTransferModes(TransferMode.ANY);
                System.out.println("Drop detected");
                event.consume();
            }
        });

        grid.add(sourcePane, 1, 1);
        grid.add(targetPane, 0, 1);
    }        
}

1 个答案:

答案 0 :(得分:0)

你需要在startDragAndDrop()之后添加一些内容,例如。 :

    sourcePane.setOnDragDetected(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            Dragboard db = sourcePane.startDragAndDrop(TransferMode.ANY);
            ClipboardContent content = new ClipboardContent();
            content.putString("Hello!");
            db.setContent(content);
            System.out.println("Drag detected");
            event.consume();
        }
    });

请参阅DragEvent上的Oracle页面:
https://docs.oracle.com/javase/8/javafx/api/javafx/scene/input/DragEvent.html