本帖最后由 HM朱蛟 于 2013-4-29 09:17 编辑
我的思路在截图上,求大神指点啊,帮忙看看我这样理解是否妥当呢?小弟先谢了{:soso_e100:}
这是代码:- /*
- 需求:在文本区域内输入一些字符,点保存后能存到硬盘上,
- 注意若文件存在不弹出对话框直接覆盖,若文件不存在直接弹出对话框。
- 在原有程序的基础上监听保存条目
- */
- import java.awt.*;
- import java.awt.event.*;
- import java.io.*;
- class Run
- {
- private Frame frame=null;
- private Menu menu=null,submenu=null;
- private MenuItem closeitem =null,subitem=null,openitem=null,saveitem=null;
- private MenuBar bar =null;
- private TextArea ta= null;
- private FileDialog openDia,saveDia;
- private File file =null;
- Run()
- {
- init();
- }
- private void init()
- {
- frame = new Frame("我的窗");
- menu = new Menu("文件菜单");
- submenu = new Menu("子菜单");
- closeitem = new MenuItem("关闭条目");
- subitem = new MenuItem("子条目");
- openitem = new MenuItem("打开条目");
- saveitem = new MenuItem("保存条目");
- bar = new MenuBar();
- ta = new TextArea();
- openDia = new FileDialog(frame,"我要打开",FileDialog.LOAD);
- saveDia = new FileDialog(frame,"我要保存",FileDialog.SAVE);//保存模式
- frame.setMenuBar(bar);
- frame.add(ta);
- bar.add(menu);
- menu.add(openitem);
- menu.add(saveitem);
- menu.add(submenu);
- submenu.add(subitem);
- menu.add(closeitem);
- frame.setBounds(500,50,500,650);
- frame.setVisible(true);
- myEvent();
- }
- private void myEvent()
- {
- //保存
- saveitem.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent ae)
- {
- if(file==null)//如果为空就弹出对话框,并将来当前文本区域内的文件封装成对象
- {
- saveDia.setVisible(true);
- String dirPath = saveDia.getDirectory();
- String fileName = saveDia.getFile();
- /*
- System.out.println("dirPath:"+dirPath); // dirPath:C:\Documents and Settings\Administrator\桌面\
- System.out.println("getFile:"+file); // getFile:null
- */
- if (dirPath == null || fileName ==null)
- return;
- //有 null
- file = new File(dirPath,fileName);
- }
- try
- {
- BufferedWriter bfw = new BufferedWriter(new FileWriter(file));
- String text = ta.getText();//获取输入内容
- bfw.write(text);
- bfw.close();
- }
- catch (Exception asd)
- {
- throw new RuntimeException();
- }
- }
- });
- //打开
- openitem.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent ae)
- {
- 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 br = new BufferedReader(new FileReader(file));
- String text=null;
- while((text=br.readLine())!=null)
- ta.append(text+"\r\n");
- }
- catch (IOException e)
- {
- throw new RuntimeException("读取失败");
- }
- }
- });
- closeitem.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent ae)
- {
- System.exit(0);
- }
- });
- frame.addWindowListener(new WindowAdapter(){
- public void windowClosing(WindowEvent we)
- {
- System.exit(0);
- }
- });
- }
- public static void main(String[] args)
- {
- new Run();
- }
- }
复制代码 |
|