本帖最后由 忄雾飞扬 于 2013-10-27 19:44 编辑
package com.jay.test1;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
public class MyMenuTest {
private Frame f;
private TextArea ta;
private MenuBar mb;
private Menu me1, me2, me3, me4, me5;
private MenuItem openMenu, saveMenu, mi3, escMenu, mi5, mi6, saveMenus;
private FileDialog opendia, savedia;
private File file;
MyMenuTest() {
init();
}
public void init() {
f = new Frame("记事本");
f.setBounds(200, 233, 666, 555);
ta = new TextArea();
mb = new MenuBar();
me1 = new Menu("文件");
me2 = new Menu("编辑");
me3 = new Menu("帮助");
me4 = new Menu("退出");
me5 = new Menu("另存为");
openMenu = new MenuItem("打开");
saveMenu = new MenuItem("保存");
mi3 = new MenuItem("求助");
escMenu = new MenuItem("退出");
mi5 = new MenuItem("复制");
mi6 = new MenuItem("粘贴");
saveMenus = new MenuItem("另存为");
me1.add(openMenu);
me1.add(me5);
me5.add(saveMenu);
me5.add(saveMenus);
me2.add(mi5);
me2.add(mi6);
me3.add(mi3);
me4.add(escMenu);
mb.add(me1);
mb.add(me2);
mb.add(me3);
mb.add(me4);
opendia = new FileDialog(f, "open");// FileDialog.LOAD
savedia = new FileDialog(f, "save", FileDialog.SAVE);
f.add(ta);
f.setMenuBar(mb);
event();
f.setVisible(true);
}
public void event() {
saveMenus.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 = new File(dirPath,fileName);
}
try{
BufferedWriter bufw = new BufferedWriter(new FileWriter(file));
String text = ta.getText();
bufw.write(text);
bufw.close();
} catch(IOException i){
throw new RuntimeException("存储出错");
}
});
openMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
opendia.setVisible(true);
String dirPath = opendia.getDirectory();
String filename = opendia.getFile();
if (dirPath == null || filename == null)
return;
ta.setText("");
file = new File(dirPath, filename);
try {
BufferedReader bufr = new BufferedReader(new FileReader(
file));
String line = null;
while ((line = bufr.readLine()) != null) {
ta.append(line + "\r\n");
}
bufr.close();
} catch (IOException i) {
throw new RuntimeException("reading....");
}
}
});
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
escMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new MyMenuTest();
}
}
|
|