经过测试是没有问题的。
代码:
package com.test.ui; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.swing.JTextArea; public class DragFile extends javax.swing.JFrame { public DragFile() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new MyTextArea(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); pack(); }// /** * @param args * the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new DragFile().setVisible(true); } }); } |
class MyTextArea extends JTextArea implements DropTargetListener {
public MyTextArea() {
new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
}
public void dragEnter(DropTargetDragEvent dtde) {
}
public void dragOver(DropTargetDragEvent dtde) {
}
public void dropActionChanged(DropTargetDragEvent dtde) {
}
public void dragExit(DropTargetEvent dte) {
}
public void drop(DropTargetDropEvent dtde) {
try {
// Transferable tr = dtde.getTransferable();
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
List list = (List) (dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor));
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
File f = (File) iterator.next();
this.append(f.getAbsolutePath() + "\n");
}
dtde.dropComplete(true);
this.updateUI();
} else {
dtde.rejectDrop();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
}
}
}
// 变量声明 - 不进行修改
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// 变量声明结束
}
···
···