我正在研究对 JList 组件的拖放支持,我希望能够支持从我的文件浏览器中拖入的文件。但是,我只想允许拖入文件而不是文件夹。因此,我试图在我的 TransferHandler 中检查它,如下所示:
@Override
public boolean canImport(TransferSupport support) {
if (support.getComponent().equals(this.resourceFileList)) {
if (!support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
} else {
try {
// get file list
Transferable transferable = support.getTransferable();
Object transferData = transferable.getTransferData(DataFlavor.javaFileListFlavor);
// check for folders
boolean containsFiles = false;
List files = (List) transferData;
for (int i = 0; i < files.size(); i++) {
File file = (File) files.get(i);
if (!file.isDirectory()) {
containsFiles = true;
}
}
// return file indicator
return containsFiles;
} catch (IOException | UnsupportedFlavorException e) {
System.out.println("Unable to check for folders due to the following exception:\n" + e);
return false;
}
}
} else {
return false;
}
}
不幸的是, transferData在这里似乎为空。然而,不是在调用 TransferHandler的importData方法时。如果这是某种错误或期望的行为,有人知道吗?
如果它有所作为并且Java版本是1.7.0_21,我在Mac(OSX 10.8)上。
提前致谢!
编辑:
这是一个简短的 SSCCE 供任何人测试。只需将文件拖入列表并观看控制台。
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.TransferHandler;
import javax.swing.TransferHandler.TransferSupport;
public class DNDIssue extends TransferHandler {
@Override
public boolean canImport(TransferSupport support) {
if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
try {
Transferable transferable = support.getTransferable();
Object transferData = transferable.getTransferData(DataFlavor.javaFileListFlavor); // <-- this returns null
System.out.println(transferData); // null
} catch (IOException | UnsupportedFlavorException e) {
System.out.println("Unable to check for folders due to the following exception:\n" + e);
} finally {
return false;
}
} else {
return false;
}
}
public static void main(String[] args) {
// create window
JFrame window = new JFrame("DNDIssue");
window.setSize(640, 480);
window.setLocation(100, 100);
// create list with model and set transfer handler
JList<File> list = new JList<File>(new DefaultListModel<File>());
list.setTransferHandler(new DNDIssue());
// add enclosing scroll pane and display window
window.getContentPane().add(new JScrollPane(list));
window.setVisible(true);
}
}