就是向图片那样直接从JTextField中读取文件名字或者路径,点击按钮就能打开文本的事件。。。
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.FileDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class OpenTxt extends JFrame{
public OpenTxt(){
super("打开文本文件");
this.setLayout(new BorderLayout());
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JButton b=new JButton("打开文本文件");
JLabel l=new JLabel("文本文件名称,位置:");
JTextField txt=new JTextField(20);
JTextArea txtContent =new JTextArea(20,10);
JScrollPane sp=new JScrollPane(txtContent);
p1.add(l);
p1.add(txt);
this.add(p1,BorderLayout.NORTH);
this.add(txtContent, BorderLayout.CENTER);
p2.add(b);
this.add(p2, BorderLayout.SOUTH);
this.setSize(500,600);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String FileName=txt.getText();
File file=new File(FileName);
String path=file.getAbsolutePath();
try {
BufferedReader br=new BufferedReader(new FileReader(path));
String result=null;
while((result=br.readLine())!=null){
txtContent.append(result);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}catch(IOException e1){
e1.printStackTrace();
}
}
});
}
public static void main(String args[]){
new OpenTxt();
}
}
我这种写法只能读取路径,不能直接读取名字~!
求大神指教~~!
谢谢