Java 拖拽文件到文本框

Java中如何把文件拖拽到文本框呢?

先看一个例子:
Java 拖拽文件到文本框
 
Java 拖拽文件到文本框
 
Java 拖拽文件到文本框
 

核心代码:

Java代码  Java 拖拽文件到文本框
  1. /*** 
  2.      * 拖拽文件到文本框 
  3.      * @param component 
  4.      */  
  5.     public void drag(final Component component)// 定义的拖拽方法  
  6.     {  
  7.         // panel表示要接受拖拽的控件  
  8.         new DropTarget(component, DnDConstants.ACTION_COPY_OR_MOVE,  
  9.                 new DropTargetAdapter() {  
  10.                     @Override  
  11.                     public void drop(DropTargetDropEvent dtde)// 重写适配器的drop方法  
  12.                     {  
  13.                         try {  
  14.                             if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor))// 如果拖入的文件格式受支持  
  15.                             {  
  16.                                 dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);// 接收拖拽来的数据  
  17.                                 List<File> list = (List<File>) (dtde  
  18.                                         .getTransferable()  
  19.                                         .getTransferData(DataFlavor.javaFileListFlavor));  
  20. //                              String temp = "";  
  21. //                              for (File file : list)  
  22. //                                  temp += file.getAbsolutePath() + ";\n";  
  23. //                              JOptionPane.showMessageDialog(null, temp);  
  24.                                 dragResponse(list,component);  
  25.                                 dtde.dropComplete(true);// 指示拖拽操作已完成  
  26.                             } else {  
  27.                                 dtde.rejectDrop();// 否则拒绝拖拽来的数据  
  28.                             }  
  29.                         } catch (Exception e) {  
  30.                             e.printStackTrace();  
  31.                         }  
  32.                     }  
  33.                 });  
  34.     }  
  35.   
  36. /*** 
  37.      * 默认实现 
  38.      */  
  39.     @Override  
  40.     protected void dragResponse(List<File> list,Component component) {  
  41.         String filePath=list.get(0).getAbsolutePath();  
  42.         if(component instanceof  JTextComponent){  
  43.             JTextComponent text=(JTextComponent)component;  
  44.             //把文本框的内容设置为拖拽文件的全路径  
  45.             text.setText(filePath);  
  46.         }  
  47.     }  

 调用:
Java 拖拽文件到文本框
 

 

项目采用maven 构建,项目结构:
Java 拖拽文件到文本框