import java.awt.*;
import java.io.*;
import java.awt.event.*;
class MyMenu05{
private Frame f;
private Menu m,subMenu;
private MenuBar mb;
private MenuItem subItem,closeItem,openItem,saveItem;
private FileDialog openDia,saveDia;
private TextArea ta;
private File file;
MyMenu05(){
init();
}
public void init(){
f = new Frame("提示信息");
m = new Menu("文件");
mb = new MenuBar();
subMenu = new Menu("父菜单");
subItem = new MenuItem("子菜单");
openItem = new MenuItem("打开");
saveItem = new MenuItem("保存");
closeItem = new MenuItem("退出");
//file = new File();
ta = new TextArea();
f.add(ta);
m.add(subItem);
subMenu.add(subItem);
m.add(closeItem);
mb.add(m);
m.add(subMenu);
m.add(openItem);
m.add(saveItem);
f.setBounds(100,100,500,400);
// f.setLayout(new FlowLayout());
openDia = new FileDialog(f,"打开",FileDialog.LOAD);
saveDia = new FileDialog(f,"保存",FileDialog.SAVE);
f.setMenuBar(mb);
f.setVisible(true);
myEvent();
}
public void myEvent(){
saveItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(file==null){
saveDia.setVisible(true);
String dirPath = saveDia.getDirectory();
String fileName = saveDia.getFile();
if(dirPath ==null || fileName==null)
return ;
File file = new File(dirPath,fileName);
try{
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write("text");
bw.close();
}
catch(IOException ex){
throw new RuntimeException("保存失败");
}
}
}
});
openItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
openDia.setVisible(true);
String dirPath = openDia.getDirectory();
String fileName = openDia.getFile();
//System.out.println(dirPath+"...."+fileName);
if(dirPath==null&&fileName==null)
return ;
ta.setText("");
File file = new File(dirPath,fileName);
try{
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while((line=br.readLine())!=null){
ta.append(line+"\r\n");
}
br.close();
}
catch(IOException ew){
throw new RuntimeException("读取失败");
}
}
});
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
closeItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
}
public static void main(String[ ]args){
new MyMenu05();
}
}
|