ドラッグ&ドロップ(DnD)でドロップされたファイル情報を取得する
DnDは、あまり使ったことありません。せいぜいmouseDraggedイベントの操作くらいで、ドロップ関連は全く触ったことがありませんでした。
というわけで練習。JFrameにExplorerなどで1つまたは複数選択したファイルをドラッグ&ドロップすると、標準出力にファイルパスが出力されます。(setDropTargetのところはこれで良いのでしょうか...)
JFrame f = new JFrame(); f.setSize(200, 200); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setDropTarget(new DropTarget(f, new DropTargetAdapter() { public void drop(DropTargetDropEvent dtde) { Transferable t = dtde.getTransferable(); if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); try { @SuppressWarnings("unchecked") List<File> fileList = (List<File>)t.getTransferData(DataFlavor.javaFileListFlavor); for (File file : fileList) { System.out.println(file); } } catch (UnsupportedFlavorException ex) { throw new RuntimeException(ex); } catch (IOException ex) { throw new RuntimeException(ex); } } } })); f.setVisible(true);
テキストエディタなどからドラッグ&ドロップしたテキストデータを取得する場合(dropメソッドのみ)。
Transferable t = dtde.getTransferable(); DataFlavor flavor = DataFlavor.selectBestTextFlavor(t.getTransferDataFlavors()); if (t.isDataFlavorSupported(flavor)) { dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); try { Object data = t.getTransferData(flavor); if (data instanceof String) { String s = (String)data; System.out.println(s); } } catch (UnsupportedFlavorException ex) { throw new RuntimeException(ex); } catch (IOException ex) { throw new RuntimeException(ex); } }