请看一下
import java.awt.*;
import java.awt.event.*;
import *;
public class NoteEdit extends Frame implements ActionListener
{
/*定义主界面,一个菜单,一个文本区*/
TextArea tArea;
MenuBar mbr;
String str,fileName;
byte byteBuf[]=new byte[10000];
FileDialog fileDlg;
NoteEdit()
{
super("记事本");
setSize(521,700);
setLocation(250,30);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{ System.exit(0); }
});
tArea=new TextArea();
add("Center",tArea);
tArea.setFont(new Font("隶书",Font.BOLD,16));
mbr=new MenuBar();
/*设置文件菜单项*/
Menu file=new Menu("文件");
MenuItem newFile=new MenuItem("新建");
MenuItem open=new MenuItem("打开");
MenuItem save=new MenuItem("保存");
MenuItem saveAs=new MenuItem("另存为");
MenuItem print=new MenuItem("打印");
MenuItem exit=new MenuItem("退出");
file.add(newFile);
file.add(open);
file.add(save);
file.add(saveAs);
file.addSeparator();
file.add(print);
file.addSeparator();
file.add(exit);
newFile.addActionListener(this);
open.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
exit.addActionListener(this);
mbr.add(file);
/*设置编辑菜单项*/
Menu edit=new Menu("编辑");
MenuItem cut=new MenuItem("剪切");
MenuItem copy=new MenuItem("复制");
MenuItem paste=new MenuItem("粘贴");
MenuItem delete=new MenuItem("删除");
edit.add(cut);
edit.add(copy);
edit.add(paste);
edit.add(delete);
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
delete.addActionListener(this);
mbr.add(edit);
/*设置格式菜单项*/
Menu model=new Menu("格式");
MenuItem font=new MenuItem("字体...");
model.add(font);
font.addActionListener(this);
mbr.add(model);
/*设置帮助菜单项*/
Menu help=new Menu("帮助");
MenuItem aboutHelp=new MenuItem("关于记事本");
help.add(aboutHelp);
aboutHelp.addActionListener(this);
mbr.add(help);
setMenuBar(mbr);
setVisible(true);
}
public static void main(String[] args)
{
new NoteEdit();
}
/*响应菜单顼事件*/
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand()=="退出")
System.exit(0);
if(e.getActionCommand()=="打开")
{
fileDlg=new FileDialog(this,"打开文件");
fileDlg.show();
fileName=fileDlg.getFile();
try{
FileInputStream in=new FileInputStream(fileName);
in.read(byteBuf);
in.close();
str=new String(byteBuf);
tArea.setText(str);
setTitle("记事本-"+fileName);
}catch(IOException ioe){}
}
if(e.getActionCommand()=="保存")
{
fileDlg=new FileDialog(this,"保存文件",FileDialog.SAVE);
fileDlg.show();
fileName=fileDlg.getFile();
str=tArea.getText();
byteBuf=str.getBytes();
try{
FileOutputStream out=new FileOutputStream(fileName);
out.write(byteBuf);
out.close();
}catch(IOException ioe){}
}
if(e.getActionCommand()=="另存为")
{
fileDlg=new FileDialog(this,"另存为",FileDialog.SAVE);
fileDlg.show();
fileName=fileDlg.getFile();
str=tArea.getText();
byteBuf=str.getBytes();
try{
FileOutputStream out=new FileOutputStream(fileName);
out.write(byteBuf);
out.close();
}catch(IOException ioe){}
}
}
}
本程序只完成了文件菜单下设置(新建末实现),其它菜单项只是一个界面而已,希望各位继续完善。