3

我尝试在网格窗格中执行拖放事件,但没有成功。检测到拖动,但未检测到拖动或放置事件。我做错了什么?

这是我尝试过的代码:

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);
    }        
}
4

1 回答 1

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();
        }
    });

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

于 2015-08-14T11:02:03.517 回答