import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
public class TextMenu extends Frame implements ActionListener {
MenuBar mb;
Menu m1,m2,m3,m4,m5,m6;
MenuItem mi11,mi12,mi13,mi14,mi15;
MenuItem mi21,mi22;
MenuItem mi31,mi32;
MenuItem mi41,mi42;
FileDialog fd,fd1;
TextArea ta;
String file="";
public TextMenu(){
super("记事本");
mb=new MenuBar();
m1=new Menu("文件(F)");
m3=new Menu("编辑(E)");
m4=new Menu("格式(O)");
m5=new Menu("查看(V)");
m6=new Menu("帮助(H)");
m2=new Menu("一级");
mi11=new MenuItem("新建(N)",new MenuShortcut(KeyEvent.VK_N));
mi12=new MenuItem("打开(O)",new MenuShortcut(KeyEvent.VK_O));
mi14=new MenuItem("保存(S)",new MenuShortcut(KeyEvent.VK_S));
mi15=new MenuItem("另存为");
mi13=new MenuItem("退出(X)",new MenuShortcut(KeyEvent.VK_X));
mi21=new MenuItem("子菜单1");
mi22=new MenuItem("子菜单2");
mi41=new MenuItem("字体");
mi42=new MenuItem("背景");
fd=new FileDialog(this,"打开(O)",FileDialog.LOAD);
fd1=new FileDialog(this,"保存(S)",FileDialog.SAVE);
mi12.addActionListener(this);
mi14.addActionListener(this);
mi15.addActionListener(this);
ta=new TextArea();
add(ta,BorderLayout.CENTER);
setMenuBar(mb);
mb.add(m1);
mb.add(m3);
mb.add(m4);
mb.add(m5);
mb.add(m6);
m1.add(mi11);
m1.add(mi12);
m1.add(mi14);
m1.add(mi15);
m1.add(m2);
m1.addSeparator();
m1.add(mi13);
m2.add(mi21);
m2.add(mi22);
m4.add(mi41);
m4.add(mi42);
mi13.addActionListener(this);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setBounds(200,200,400,300);
setVisible(true);
}
public static void main(String[] args) {
new TextMenu();
}
public void actionPerformed(ActionEvent e) {
String str=e.getActionCommand();
if(str.equals("退出(X)")){
System.exit(0);
}else if(str.equals("打开(O)")){
fd.setVisible(true);
String d=fd.getDirectory();
String f=fd.getFile();
if(d!=null&&f!=null){
file=d+f;
loadFile();
}
}else if(str.equals("保存(S)")){
if(file==null||file.equals("")){
saveFileAs();
}else{
saveFile();
}
}else if(str.equals("另存为")){
saveFileAs();
}
}
public void loadFile(){
ta.setText("");
this.setTitle("记事本--"+file);
try{
BufferedReader br=new BufferedReader(new FileReader(file));
String s=br.readLine();
while(s!=null){
ta.append(s+"\n");
s=br.readLine();
}
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
public void saveFile(){
String content=ta.getText();
try{
PrintWriter pw=new PrintWriter(new FileWriter(file));
pw.println(content);
pw.close();
}catch(IOException e){
e.printStackTrace();
}
}
public void saveFileAs(){
fd1.setVisible(true);
String d=fd1.getDirectory();
String f=fd1.getFile();
if((d!=null)&&(f!=null)){
file=d+f;
saveFile();
setTitle("记事本--"+file);
}
}
}