5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaFXでファイルのドラッグ&ドロップ

Posted at

内容

ファイルがドラッグ&ドロップされたらそのファイルの絶対パスを表示するプログラム。

コード

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

補足

ファイルをドラッグ&ドロップするだけでもsetOnDragOverメソッド内でacceptTransferModesを呼び出す記述が必要。ないと動かない。

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?