Drag and drop files with JavaFX

Contents

A program that displays the absolute path of a file when it is dragged and dropped.

code

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

Supplement

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

Drag and drop files with JavaFX
[Rails] Implementation of drag and drop function (with effect)
Hello world with Kotlin and JavaFX
[Java] Reading and writing files with OpenCSV
JavaFX and HiDPI
Hello world with Kotlin and JavaFX
Drag and drop files with JavaFX
Scaling and translation with JavaFX Canvas (Revenge)
JavaFX and HiDPI
HelloFX with JavaFX
A simple rock-paper-scissors game with JavaFX and SceneBuilder
[Review] Reading and writing files with java (JDK6)
Merry Christmas with JavaFX !!
Introduce JavaFX 15 and do GUI development with VS Code
Connect with port forwarding with SSH and send and receive files
Prepare the environment for java11 and javaFx with Ubuntu 18.4
[Java] Development with multiple files using package and import
Make an Ev3 radio control with JavaFx and leJOS [Part 2]
Getting started with Java and creating an AsciiDoc editor with JavaFX
[Swift] You can concatenate cells with Drag & Drop of UITableView
Make an Ev3 radio control with JavaFx and leJOS [Part 1]
URLSession with URLSession and Combine normally
[Note] Scene transition with JavaFX