I found this tutorial: Drag and dropping files to a Java desktop application
It correctly shows the panel and enables the drop-and-dragging but it sends out error
Can only iterate over an array or an instance of java.lang.Iterable
referring to the passage:
for (File file : files) {
// Print out the file path
System.out.println("File path is '" + file.getPath() + "'.");
}
I really don't know how to solve the problem... Could you plese help me?
Update:
If I try doing this:
List File[] files = (File[]) transferable.getTransferData(flavor);
it keeps giving me an error...
So I tried doing this:
File[] files = (File[]) transferable.getTransferData(flavor);
and the code is no longer underlined but it keeps not working.
I also found another tutorial:
how to drag and drop files from a directory in java
It doesn't work of course -.-'
I think the closest thing I have to the solution is this complete example:
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.swing.*;
@SuppressWarnings("serial")
public class FileDragDemo extends JPanel {
private JList list = new JList();
public FileDragDemo() {
list.setDragEnabled(true);
list.setTransferHandler(new FileListTransferHandler(list));
add(new JScrollPane(list));
}
private static void createAndShowGui() {
FileDragDemo mainPanel = new FileDragDemo();
JFrame frame = new JFrame("FileDragDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
@SuppressWarnings("serial")
class FileListTransferHandler extends TransferHandler {
private JList list;
public FileListTransferHandler(JList list) {
this.list = list;
}
public int getSourceActions(JComponent c) {
return COPY_OR_MOVE;
}
public boolean canImport(TransferSupport ts) {
return ts.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}
public boolean importData(TransferSupport ts) {
try {
@SuppressWarnings("rawtypes")
List data = (List) ts.getTransferable().getTransferData(
DataFlavor.javaFileListFlavor);
if (data.size() < 1) {
return false;
}
DefaultListModel listModel = new DefaultListModel();
for (Object item : data) {
File file = (File) item;
listModel.addElement(file);
}
list.setModel(listModel);
return true;
} catch (UnsupportedFlavorException e) {
return false;
} catch (IOException e) {
return false;
}
}
}
The only problem is that I want the panel to show all the images I upload, instead it only displays the last entry