Java中如何把文件拖拽到文本框呢?
先看一个例子:
核心代码:
Java代码 /****拖拽文件到文本框*@paramcomponent*/publicvoiddrag(finalComponentcomponent)//定义的拖拽方法{//panel表示要接受拖拽的控件newDropTarget(component,DnDConstants.ACTION_COPY_OR_MOVE,newDropTargetAdapter(){@Overridepublicvoiddrop(DropTargetDropEventdtde)//重写适配器的drop方法{try{if(dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor))//如果拖入的文件格式受支持{dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);//接收拖拽来的数据List<File>list=(List<File>)(dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor));//Stringtemp="";//for(Filefile:list)//temp+=file.getAbsolutePath()+";\n";//JOptionPane.showMessageDialog(null,temp);dragResponse(list,component);dtde.dropComplete(true);//指示拖拽操作已完成}else{dtde.rejectDrop();//否则拒绝拖拽来的数据}}catch(Exceptione){e.printStackTrace();}}});}/****默认实现*/@OverrideprotectedvoiddragResponse(List<File>list,Componentcomponent){StringfilePath=list.get(0).getAbsolutePath();if(componentinstanceofJTextComponent){JTextComponenttext=(JTextComponent)component;//把文本框的内容设置为拖拽文件的全路径text.setText(filePath);}}
调用:
项目采用maven构建,项目结构: