import java.awt.BorderLayout;
import java.awt.Desktop;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.function.Consumer;
import javax.swing.*;
public class Test {
static class FileTransferHandler extends TransferHandler {
private Consumer<List<File>> consumer;
public FileTransferHandler(Consumer<List<File>> consumer) {
this.consumer = consumer;
}
public boolean canImport(TransferSupport support) {
return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}
@SuppressWarnings("unchecked")
public boolean importData(TransferSupport support) {
if (!canImport(support)) {
return false;
}
Transferable t = support.getTransferable();
try {
List<File> files = (List<File>) t.getTransferData(DataFlavor.javaFileListFlavor);
consumer.accept(files);
return true;
} catch (UnsupportedFlavorException | IOException | RuntimeException ex) {
ex.printStackTrace();
return false;
}
}
}
private JLabel attachment = new JLabel();
private File attached;
private void importFiles(List<File> files) {
if (files.isEmpty()) { return; }
File f = files.get(0);
setAttachment(f);
}
private void setAttachment(File file) {
attachment.setText(file == null ? "" : file.toString());
attached = file;
}
private void openAttachment() {
if (attached != null) {
try {
Desktop.getDesktop().open(attached);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void run() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createTitledBorder("Drop here"));
panel.setTransferHandler(new FileTransferHandler(this::importFiles));
panel.add(attachment);
attachment.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
openAttachment();
}
});
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(panel);
frame.setSize(800, 600);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Test().run());
}
}