Drag get file path
In windows software, many software provides drag a file to open the file functions, in JavaFx also have this feature, it is achieved through the listener
Monitor
setOnDragDetected (new EventHandler ());
When you drag from a Node, it detects the drag operation will be performed this EventHandler.setOnDragEntered (new EventHandler ());
When you drag target control when this event will execute the callback.setOnDragExited (new EventHandler ());
When you drag out of the target control, perform this operation.setOnDragOver (new EventHandler ());
When you drag over the target time, will not stop the execution.setOnDragDropped (new EventHandler ());
When you release the mouse button and drag to the target time to implement this DragDropped event.setOnDragDone (new EventHandler ());
When you drag and let go of time to implement Drag to complete the operation.
I use a method fxml binding events, the above setOnDragDropped
and setOnDragDone
set methods, but just could not execute, I do not know why. I finally used setOnDragExited
the listener.
Code
Let's set the listener through fxml in.
It can be set directly in the scenebuilder direct method
or another fxml file, write the code onDragExited="#getFile"
, and then to create getFile method can be.
@FXML
void getFile(DragEvent event) {
List<File> files = event.getDragboard().getFiles();
//获得文件
File file = files.get(0);
//之后的相关操作,获得文件路径等..
}