我正在制作Java程序,加载文件的一种方法是将文件拖到应用程序窗口(swing)。我的代码适用于Windows和Linux。它适用于OS X,但我拖动的第一个文件抛出一个异常,然后其余的工作正常。
以下是我用来启用DnD的代码。
/*
* Allow a file to be opened by dragging it onto the window
*/
public void drop(DropTargetDropEvent dtde){
try {
// Get the object to be transferred
Transferable tr = dtde.getTransferable();
DataFlavor[] flavors = tr.getTransferDataFlavors();
// If flavors is empty get flavor list from DropTarget
flavors = (flavors.length == 0) ? dtde.getCurrentDataFlavors() : flavors;
// Select best data flavor
DataFlavor flavor = DataFlavor.selectBestTextFlavor(flavors);
// Flavor will be null on Windows
// In which case use the 1st available flavor
flavor = (flavor == null) ? flavors[0] : flavor;
// Flavors to check
DataFlavor Linux = new DataFlavor("text/uri-list;class=java.io.Reader");
DataFlavor Windows = DataFlavor.javaFileListFlavor;
// On Linux (and OS X) file DnD is a reader
if(flavor.equals(Linux)) {
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
BufferedReader read = new BufferedReader(flavor.getReaderForText(tr));
// Remove 'file://' from file name
String fileName = read.readLine().substring(7).replace("%20"," ");
// Remove 'localhost' from OS X file names
if(fileName.substring(0,9).equals("localhost")) {
fileName = fileName.substring(9);
}
read.close();
dtde.dropComplete(true);
System.out.println("File Dragged:" + fileName);
mainWindow.openFile(fileName);
}
// On Windows file DnD is a file list
else if(flavor.equals(Windows)) {
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
@SuppressWarnings("unchecked")
List<File> list = (List<File>)tr.getTransferData(flavor);
dtde.dropComplete(true);
if(list.size() == 1) {
System.out.println("File Dragged: " + list.get(0));
mainWindow.openFile(list.get(0).toString());
}
} else {
System.err.println("DnD Error");
dtde.rejectDrop();
}
}
//TODO: OS X Throws ArrayIndexOutOfBoundsException on first DnD
catch(ArrayIndexOutOfBoundsException e){
System.err.println("DnD not initalized properly, please try again.");
} catch(IOException e){
System.err.println(e.getMessage());
} catch(UnsupportedFlavorException e){
System.err.println(e.getMessage());
} catch (ClassNotFoundException e){
System.err.println(e.getMessage());
}
}
出于某种原因,OS X在此行上抛出ArrayIndexOutOfBoundsException:
flavor = (flavor == null) ? flavors[0] : flavor;
抛出异常后,如果我将另一个文件拖到窗口上,它就可以了。为什么会抛出异常?
注意:mainWindow.openFile()是一个打开文件的函数。它需要一个字符串参数(文件名),程序打开该文件。
注意2:这是在OS X 10.6.2(Snow Leopard)上。
答案 0 :(得分:4)
我也有这个问题,但它似乎是用最新的java版本修复的:
ray@featuritis:~/projects>java -version
java version "1.6.0_17"
Java(TM) SE Runtime Environment (build 1.6.0_17-b04-248-10M3025)
Java HotSpot(TM) 64-Bit Server VM (build 14.3-b01-101, mixed mode)