日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

Java 拖拽文件到文本框

發(fā)布時間:2025/5/22 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java 拖拽文件到文本框 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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

先看一個例子:

?

?

?

核心代碼:

Java代碼??
  • /***?
  • ?????*?拖拽文件到文本框?
  • ?????*?@param?component?
  • ?????*/??
  • ????public?void?drag(final?Component?component)//?定義的拖拽方法??
  • ????{??
  • ????????//?panel表示要接受拖拽的控件??
  • ????????new?DropTarget(component,?DnDConstants.ACTION_COPY_OR_MOVE,??
  • ????????????????new?DropTargetAdapter()?{??
  • ????????????????????@Override??
  • ????????????????????public?void?drop(DropTargetDropEvent?dtde)//?重寫適配器的drop方法??
  • ????????????????????{??
  • ????????????????????????try?{??
  • ????????????????????????????if?(dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor))//?如果拖入的文件格式受支持??
  • ????????????????????????????{??
  • ????????????????????????????????dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);//?接收拖拽來的數(shù)據(jù)??
  • ????????????????????????????????List<File>?list?=?(List<File>)?(dtde??
  • ????????????????????????????????????????.getTransferable()??
  • ????????????????????????????????????????.getTransferData(DataFlavor.javaFileListFlavor));??
  • //??????????????????????????????String?temp?=?"";??
  • //??????????????????????????????for?(File?file?:?list)??
  • //??????????????????????????????????temp?+=?file.getAbsolutePath()?+?";\n";??
  • //??????????????????????????????JOptionPane.showMessageDialog(null,?temp);??
  • ????????????????????????????????dragResponse(list,component);??
  • ????????????????????????????????dtde.dropComplete(true);//?指示拖拽操作已完成??
  • ????????????????????????????}?else?{??
  • ????????????????????????????????dtde.rejectDrop();//?否則拒絕拖拽來的數(shù)據(jù)??
  • ????????????????????????????}??
  • ????????????????????????}?catch?(Exception?e)?{??
  • ????????????????????????????e.printStackTrace();??
  • ????????????????????????}??
  • ????????????????????}??
  • ????????????????});??
  • ????}??
  • ??
  • /***?
  • ?????*?默認(rèn)實(shí)現(xiàn)?
  • ?????*/??
  • ????@Override??
  • ????protected?void?dragResponse(List<File>?list,Component?component)?{??
  • ????????String?filePath=list.get(0).getAbsolutePath();??
  • ????????if(component?instanceof??JTextComponent){??
  • ????????????JTextComponent?text=(JTextComponent)component;??
  • ????????????//把文本框的內(nèi)容設(shè)置為拖拽文件的全路徑??
  • ????????????text.setText(filePath);??
  • ????????}??
  • ????}??
  • ?調(diào)用:

    ?

    ?

    項(xiàng)目采用maven?構(gòu)建,項(xiàng)目結(jié)構(gòu):

    總結(jié)

    以上是生活随笔為你收集整理的Java 拖拽文件到文本框的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。