代码如下:
package IO;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class notepad extends JFrame implements ActionListener{
/**
* @param args
*/
JTextArea jta=null;
// 定义菜单条
JMenuBar jmb=null;
JMenu jm1=null;
JMenuItem jmi1=null;
JMenuItem jmi2=null;
public static void main(String[] args) {
// TODO Auto-generated method stub
notepad np=new notepad();
}
public notepad(){
jta=new JTextArea();
jmb=new JMenuBar();
jm1=new JMenu("文件");
// 设置助记符
jm1.setMnemonic('F');
jmi1=new JMenuItem("打开",new ImageIcon("2.png"));
jmi1.addActionListener(this);
jmi1.setActionCommand("open");
jmi2=new JMenuItem("保存",new ImageIcon("3.png"));
jmi2.addActionListener(this);
jmi2.setActionCommand("save");
this.setJMenuBar(jmb);
jmb.add(jm1);
jm1.add(jmi1);
jm1.add(jmi2);
this.add(jta);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400,300);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
// 判断是哪一个操蛋被选中
if(e.getActionCommand().equals("open")){
// System.out.print("打开");
JFileChooser jfc1=new JFileChooser();
jfc1.setDialogTitle("请选择文件");
jfc1.showOpenDialog(null);
// 显示
jfc1.setVisible(true);
// 得到选择的路径
String filename=jfc1.getSelectedFile().getAbsolutePath();
System.out.print(filename);
FileReader fr=null;
BufferedReader br=null;
try {
fr=new FileReader(filename);
br=new BufferedReader(fr);
// 显示打印信息
String s="";
String allCon="";
while((s=br.readLine())!=null){
// bw.write(s+"\r\n");
allCon+=s+"\r\n";
}
// 繁重到
jta.setText(allCon);
} catch (Exception e2) {
// TODO: handle exception
}finally{
try {
br.close();
fr.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}else if(e.getActionCommand().equals("save")){
JFileChooser jfc=new JFileChooser();
jfc.setDialogTitle("另存为...");
jfc.showSaveDialog(null);
jfc.setVisible(true);
// 把文件保存打响应位置
String file=jfc.getSelectedFile().getAbsolutePath();
// 写入到指定的额文件
FileWriter fw=null;
BufferedWriter bw=null;
try {
fw=new FileWriter(file);
bw=new BufferedWriter(fw);
bw.write(this.jta.getText());
} catch (Exception e2) {
// TODO: handle exception
}finally{
try {
fw.close();
bw.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}