生活随笔
收集整理的這篇文章主要介紹了
Java 拖拽文件到文本框
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Java中如何把文件拖拽到文本框呢?
先看一個例子:
?
?
?
核心代碼:
Java代碼??
?????????public?void?drag(final?Component?component)??????{????????????????????new?DropTarget(component,?DnDConstants.ACTION_COPY_OR_MOVE,??????????????????new?DropTargetAdapter()?{??????????????????????@Override??????????????????????public?void?drop(DropTargetDropEvent?dtde)??????????????????????{??????????????????????????try?{??????????????????????????????if?(dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor))??????????????????????????????{??????????????????????????????????dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);??????????????????????????????????List<File>?list?=?(List<File>)?(dtde??????????????????????????????????????????.getTransferable()??????????????????????????????????????????.getTransferData(DataFlavor.javaFileListFlavor));??????????????????????????????????????????dragResponse(list,component);??????????????????????????????????dtde.dropComplete(true);??????????????????????????????}?else?{??????????????????????????????????dtde.rejectDrop();??????????????????????????????}??????????????????????????}?catch?(Exception?e)?{??????????????????????????????e.printStackTrace();??????????????????????????}??????????????????????}??????????????????});??????}????????????@Override??????protected?void?dragResponse(List<File>?list,Component?component)?{??????????String?filePath=list.get(0).getAbsolutePath();??????????if(component?instanceof??JTextComponent){??????????????JTextComponent?text=(JTextComponent)component;????????????????????????????text.setText(filePath);??????????}??????}?? ?調用:
?
?
項目采用maven?構建,項目結構:
總結
以上是生活随笔為你收集整理的Java 拖拽文件到文本框的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。