I have created a Swing application that can import images into a label, but what I want to do is to put the imported image into an internal frame that will be created after the image is dropped.
- Drop an image into the Java app
- Create a
JInternalFrame - Make the image appear in the internal frame instead of the label in the
JFrame
public class Test{
public static void main(String[] args) {
JFrame f = new JFrame("Testing");
JLabel l = new JLabel("Drop here");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(600, 600);
f.setLocationRelativeTo(null);
f.setVisible(true);
f.add(l);
l.setHorizontalAlignment(JLabel.CENTER);
l.setTransferHandler(new TransferHandler() {
private static final long serialVersionUID = 1L;
public static final DataFlavor[] SUPPORTED_DATA_FLAVORS = new DataFlavor[]{
DataFlavor.javaFileListFlavor,
DataFlavor.imageFlavor
};
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
System.out.println("1");
for (DataFlavor flavor : SUPPORTED_DATA_FLAVORS) {
if (!support.isDataFlavorSupported(flavor)) {
return true;
}
}
return true;
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
System.out.println("2");
new Test();
JInternalFrame mb = new JInternalFrame("Frame title4", true, true, true);
JLabel la = new JLabel("here");
mb.setSize(400, 300);
l.add(mb);
la.setHorizontalAlignment(JLabel.CENTER);
mb.add(la);
mb.setVisible(true);
if (canImport(support)) {
try {
Transferable t = support.getTransferable();
Component component = support.getComponent();
if (component instanceof JLabel) {
Image image = null;
if (support.isDataFlavorSupported(DataFlavor.imageFlavor)) {
image = (Image) t.getTransferData(DataFlavor.imageFlavor);
} else if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
@SuppressWarnings("rawtypes")
List files = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
if (files.size() > 0) {
image = ImageIO.read((File) files.get(0));
}
}
ImageIcon icon = null;
if (image != null) {
icon = new ImageIcon(image);
}
((JLabel) component).setIcon(icon);
return true;
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
return true;
}
});
}}
Drop and image on a frame, panel, label, internal frame, is all effectively the same thing. For me, I'd focus on common denominator to make things easier, for me, this means a
JPanel.A
JPanelcan be added to a frame, internal frame another panel/container and can make decisions about how to present the drop, in this case, it can use aJLabelto present an image.So, based on how to drag and drop files from a directory in java and Java Drag-n-Drop files of specific extension on JFrame
You could do something like...
nb: On MacOS, you can't pre-process the
Transferabledata. It did work on Windows way back when I was using Windows 7, I can't verify if it still works.