A program that displays the absolute path of a file when it is dragged and dropped.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
VBox root = new VBox();
root.setOnDragOver(event -> {
Dragboard board = event.getDragboard();
if (board.hasFiles()) {
event.acceptTransferModes(TransferMode.MOVE);
}
});
root.setOnDragDropped(event -> {
Dragboard board = event.getDragboard();
if (board.hasFiles()) {
board.getFiles().forEach(file -> {
root.getChildren().add(new Label(file.getAbsolutePath()));
System.out.println(file.getAbsolutePath());
});
event.setDropCompleted(true);
} else {
event.setDropCompleted(false);
}
});
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
You need a description to call ʻacceptTransferModes in the
setOnDragOver` method just by dragging and dropping the file. It doesn't work without it.
Recommended Posts