import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class ReaderListen implements ActionListener
{
JTextField textInput;
JTextArea textshow;
//两个方法,将窗口类中的两个参数传入
public void setJTextField(JTextField text)
{
textInput = text;
}
public void setJTextArea(JTextArea area)
{
textshow = area;
}
public void actionPerformed(ActionEvent e)//重写接口中的方法
{
textshow.setText(null);//setText()方法,设置当前对象的内容,相当于初始化
try
{
File file = new File(textInput.getText());//将通过textInput获取的字符串创建一个文件
//getText()方法,获取对象的文本内容
FileReader in = new FileReader(file);//字符输入流
BufferedReader in2 = new BufferedReader(in);
String s = null;
while((s=in2.readLine())!=null)
{
textshow.append(s+"\n");//append()方法,向当前字符串追加字符,读到每行结尾添加一个换行符
}
in.close();//关闭字符流
in2.close();
}
catch(IOException exp)//处理异常
{
textshow.append(exp.toString());
}
}
}
import java.awt.*;
import javax.swing.*;
public class windowActionEvent extends JFrame
{
JTextField text;//创建文本框
JTextArea textshow;//创建显示文件字符的文本区
JButton button;//创建按钮
ReaderListen listener = new ReaderListen();//创建监视器?可能是吧
//构造方法中不要加返回值类型
//否则不是构造方法,而是普通方法
public windowActionEvent()
{
init();//初始化窗口的具体方法
setVisible(true);//窗体可见
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭操作
}
public void init()//构造方法调用
{
//改变窗体的布局可以通过建立空的标签占位置
setLayout(new FlowLayout());//采用默认布局模式,从第一行开始,排满第一行,开始第二行
add(new JLabel("请输入文件名"));
text = new JTextField(10);//设置文本框长度
add(text);//向底层容器加入文本框
button = new JButton("打开");
add(button);
textshow = new JTextArea(32,65);//构造方法,第一个参数为行数,第二个是列数
add(new JScrollPane(textshow));//创建一个带滚动条的面板,向面板中加入textshow文本区域
//为对象设置参数
listener.setJTextField(text);//将text作为参数传入ReaderListen类
listener.setJTextArea(textshow);//将textshow传入
text.addActionListener(listener);//text是事件源,listener是监视器
button.addActionListener(listener);//button是事件源,listener是监视器
//参数是实现接口的一个实例
}
}
public class Main
{
public static void main(String[] args)
{
windowActionEvent win = new windowActionEvent();
win.setBounds(300,20,800,700);//窗体的尺寸
win.setTitle("文件阅读器");//窗体的名字
}
}
界面(缩小版)