- //package mymenu;
- import java.awt.*;
- import java.awt.event.*;
- import java.io.*;
- public class MyMenuTest
- {
- private Frame f;
- private MenuBar bar;
- private TextArea ta;
- private Menu fileMenu;
- private MenuItem openItem,saveItem,closeItem;
- private FileDialog openDia,saveDia;
- private File file;
- MyMenuTest()
- {
- init();//初始化
- }
- public void init()
- {
- //主窗口基本设置
- f=new Frame("my window");
- f.setBounds(200,100,700,550);
- bar=new MenuBar();
- ta=new TextArea();
- fileMenu=new Menu("文件");
- openItem=new MenuItem("打开");
- saveItem=new MenuItem("保存");
- closeItem=new MenuItem("关闭");
- //把三个菜单项openItem,saveItem,closeItem添加到菜单中
- fileMenu.add(openItem);
- fileMenu.add(saveItem);
- fileMenu.add(closeItem);
- //创建菜单
- bar.add(fileMenu);
- f.setMenuBar(bar);
- //打开,保存窗口设置
- openDia=new FileDialog(f,"我要打开",FileDialog.LOAD);
- saveDia=new FileDialog(f,"我要保存",FileDialog.SAVE);
- f.add(ta);
- myEvent();
- f.setVisible(true);
- }
- private 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=new File(dirPath,fileName);
- }
- try
- {
- //写入到文件中
- BufferedWriter bufw=new BufferedWriter(new FileWriter(file));
- String text=ta.getText();
- bufw.write(text);
- bufw.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();
- if(dirPath==null||fileName==null)
- return ;
- //每次打开操作之前都清空ta文本内容
- 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 ex)
- {
- throw new RuntimeException("读取失败");
- }
- }
- });
- //'关闭'菜单项执行关闭操作
- closeItem.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- System.exit(0);
- }
- });
- //frame窗口的'X'操作
- f.addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- System.exit(0);
- }
- });
- }
- public static void main(String[] args)
- {
- new MyMenuTest();
- }
- }
复制代码
|
|