简体   繁体   中英

JTable using Swings Drag and Drop Files

I'm creating a MusicPlayer GUI which implements a Drag and Drop File onto the table which allows

public void drop(DropTargetDropEvent dtde){
            dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
            Transferable t = dtde.getTransferable();
            try {
                List fileList = (List)t.getTransferData(DataFlavor.javaFileListFlavor);
                File f = (File)fileList;
                addDnDFile(fileList);
            } catch (UnsupportedFlavorException ex) {
            } catch (IOException ex) {
            }

        }

As of right now I can't seem to figure out any possible way to convert a List into a File to be able to use my addDnDFile method which adds the file to my musicplayer.

A List is obviously not a File , it's a List of File s

Unfortunately, this was before we got generics ;), but basically, you want to iterate over the List and check that each entry is actually a File and deal with it in whatever manner you want, for example

@Override
public synchronized void drop(DropTargetDropEvent dtde) {
    if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
        dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
        Transferable t = dtde.getTransferable();
        List fileList = null;
        try {
            fileList = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
            if (fileList != null && fileList.size() > 0) {
                for (Object value : fileList) {
                    if (value instanceof File) {
                        File f = (File) value;
                        if (row < 0) {
                            model.addRow(new Object[]{f.getAbsolutePath(), "", f.length(), "", ""});
                        } else {
                            model.insertRow(row, new Object[]{f.getAbsolutePath(), "", f.length(), "", ""});
                            row++;
                        }
                    }
                }
            }
        } catch (UnsupportedFlavorException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        dtde.rejectDrop();
    }
}

For a runnable example, you can check out drag and drop files from OS into JTable java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM