前面学习了文件IUO流,现在制作一个记事本,作为对前面知识的巩固。
案例:NotePad
功能:实现记事本 打开文本文件、保存文本文件的功能。
public class Test extends JFrame implements ActionListener{
//定义
JMenuBar jmb =null;
JMenu jm1 = null;
JMenuItem jmi1,jmi2,jmi3 =null;
JTextArea jta = null;
public static void main(String[] args) {
Test t = new Test();
}
//构造
public Test(){
jta = new JTextArea();
jmb = new JMenuBar();
jm1 = new JMenu("文件");
jmi1 = new JMenuItem("打开");
//注册监听
jmi1.addActionListener(this);
jmi1.setActionCommand("open");
jmi2 = new JMenuItem("保存");
jmi2.addActionListener(this);
jmi2.setActionCommand("save");
jmi3 = new JMenuItem("退出");
jmi3.addActionListener(this);
jmi3.setActionCommand("exit");
this.add(jta);
this.setJMenuBar(jmb);
jmb.add(jm1);
jm1.add(jmi1);
jm1.add(jmi2);
jm1.add(jmi3);
//设置窗体属性
this.setSize(400,300);
this.setLocation(500, 200);
this.setTitle("NotePad");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent ae) {
// TODO Auto-generated method stub
if(ae.getActionCommand().equals("open")){
//打开窗口
JFileChooser jfcr = new JFileChooser();
//设置窗体名称
jfcr.setDialogTitle("请选择文件……");
//设置窗口格式
jfcr.showOpenDialog(null);
jfcr.setVisible(true);
//得到选择文件的绝对路径
String file = jfcr.getSelectedFile().getAbsolutePath();
//读取文件
FileReader fr =null;
BufferedReader br = null;
try {
fr = new FileReader(file);
br = new BufferedReader(fr);
//读取
String s = "";
String allCon = "";
//循环读取
while((s=br.readLine())!=null){
allCon+= s+ "\r\n";
}
//显示到jta
jta.setText(allCon);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fr.close();
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else if(ae.getActionCommand().equals("save")){
// System.out.println("save");
//设置窗体属性
JFileChooser jfcr = new JFileChooser();
//设置窗体名称
jfcr.setDialogTitle("请选择保存的路径……");
//设置窗体
jfcr.showOpenDialog(null);
jfcr.setVisible(true);
//得到文件的绝对路径
String file = jfcr.getSelectedFile().getAbsolutePath();
FileWriter fw = null;
BufferedWriter bw =null;
try {
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
//写进去
bw.write(jta.getText());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
bw.close();
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else if(ae.getActionCommand().equals("exit")){
System.out.println("Exit");
}
}
}