java文件拖动
- 提问者网友:骨子里的高雅
- 2021-04-22 16:12
- 五星知识达人网友:患得患失的劫
- 2021-04-22 17:33
读取拖放文件的,你参考 下:
txt.setTransferHandler(new TextTransferHandler(txt));
package com.pad;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JTextArea;
import javax.swing.TransferHandler;
public class TextTransferHandler extends TransferHandler{
private JTextArea Text;
public TextTransferHandler(JTextArea Text) {
this.Text=Text;
}
public boolean canImport(JComponent c,DataFlavor[] flavors) {
for(int i=0;i<flavors.length;i++) {
if(DataFlavor.javaFileListFlavor.equals(flavors[i])) {
return true;
}
}
return false;
}
public boolean importData(JComponent c,Transferable t) {
try {
List<?> files=(List<?>)t.getTransferData(DataFlavor.javaFileListFlavor);
addFilesToFilePathList(files);
} catch(UnsupportedFlavorException ufe) {
ufe.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
}
return false;
}
private void addFilesToFilePathList(List<?> files) {
for(Iterator<?> iter=files.iterator();iter.hasNext();) {
File file=(File)iter.next();
String str=null;
try {
FileReader fr=new FileReader(file);
BufferedReader bfr=new BufferedReader(fr);
Text.setText(null);
while((str=bfr.readLine())!=null) {
Text.append(str+"\15\12");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
- 1楼网友:英雄的欲望
- 2021-04-22 18:31
- 2楼网友:野味小生
- 2021-04-22 17:46