package notepad;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class NotePad extends JFrame implements ActionListener{
JTextArea jta = null;
JMenuBar jmb = null;
JMenu jm = null;
JMenuItem jm1 = null;
JMenuItem jm2 = null;
public static void main(String[] args) {
NotePad np = new NotePad();
}
public NotePad() {
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jta = new JTextArea();
jmb = new JMenuBar();
jm = new JMenu("文件");
//设置助记符(单引号)
jm.setMnemonic('F');
jm1 = new JMenuItem("打开");
//注册监听器
jm1.addActionListener(this);
jm1.setActionCommand("open");
jm2 = new JMenuItem("保存");
//注册监听器
jm2.addActionListener(this);
jm2.setActionCommand("save");
//将组建添加到JFrame中
jm.add(jm1);
jm.add(jm2);
jmb.add(jm);
setJMenuBar(jmb);
add(jta);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
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 (IOException ex) {
Logger.getLogger(NotePad.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
fw.close();
bw.close();
} catch (IOException ex) {
Logger.getLogger(NotePad.class.getName()).log(Level.SEVERE, null, ex);
}
}
}else
if(e.getActionCommand().equals("open"));
{
//文件选择组建
JFileChooser jfc=new JFileChooser();
jfc.setDialogTitle("请选择组建:");
//按默认的方式显示
jfc.showOpenDialog(null);
jfc.setVisible(true);
String filename=jfc.getSelectedFile().getAbsolutePath();
FileReader fr=null;
BufferedReader br=null;
try {
fr=new FileReader(filename);
br=new BufferedReader(fr);
String s="";
String con="";
try {
while((s=br.readLine())!=null)
{
con+=s+"\r\n";