初学图形化界面的一个小程序出了点问题
- Java code
import java.awt.*;import java.awt.event.*;import java.io.*;class MenuDemo{ private Frame f; private MenuBar mb; private Menu m; private MenuItem dm,gm,bm; private FileDialog open,save; private TextArea ta; private File file; MenuDemo() { init(); } public void init() { f=new Frame("魔兽世界"); mb=new MenuBar(); m=new Menu("文件"); dm=new MenuItem("打开"); gm=new MenuItem("退出"); bm=new MenuItem("保存"); open=new FileDialog(f,"打开WoW",FileDialog.LOAD); save=new FileDialog(f,"关闭WoW",FileDialog.SAVE); ta=new TextArea(); f.setBounds(300,100,600,600); //f.setLayout(new FlowLayout());使用默认布局,没设置东南西北,就填充了 f.setMenuBar(mb); f.add(ta); mb.add(m); m.add(dm); m.add(bm); m.add(gm); myEvent(); f.setVisible(true); } private void myEvent() { bm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(file==null) { save.setVisible(true); String s1=save.getFile(); String s2=save.getDirectory(); if (s1==null||s2==null) { return; } file=new File(s2,s1); } else { BufferedWriter bw=null; try { bw=new BufferedWriter(new FileWriter(file)); String s=ta.getText(); bw.write(s); bw.flush(); bw.close(); } catch (IOException e1) { throw new RuntimeException("写入失败"); } } } }); dm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { open.setVisible(true); String filePath=open.getDirectory(); String name=open.getFile(); if (filePath==null||name==null) { return; } ta.setText(""); file=new File(filePath,name); BufferedReader br=null; try { br=new BufferedReader(new FileReader(file)); String line=null; while ((line=br.readLine())!=null) { ta.append(line+"\r\n"); } } catch (IOException e1) { throw new RuntimeException("读取失败"); } finally { try { if (br!=null) { br.close(); } } catch (IOException e1) { System.out.println("读取流关闭失败"); } } } }); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); gm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); } public static void main(String[] args) { new MenuDemo(); }}
这个程序实现了非常简易的记事本功能,只有保存,读取,和退出功能,但是如果不打开文件,而是直接在这个程序里的文本区域里写一些东西按保存后,这个文件是没有立刻出现的,而需要再一次按保存才出现,小弟实在不知道为什么。求大神解惑。(也就是说当我直接在文本区域里写了一些数据后,需要按2次保存才能看到这个文件的出现。)
[解决办法]
用了if,else 语句,所以第一次file=null,就跳过了。第二次报错才执行save操作,注释掉就好了。
- Java code
if(file==null) { save.setVisible(true); String s1=save.getFile(); String s2=save.getDirectory(); if (s1==null||s2==null) { return; } file=new File(s2,s1); if(!file.exists()){ try { file.createNewFile(); } catch (IOException e1) { e1.printStackTrace(); } } } // else //{ BufferedWriter bw=null; try { bw=new BufferedWriter(new FileWriter(file)); String s=ta.getText(); bw.write(s); bw.flush(); bw.close(); } catch (IOException e1) { throw new RuntimeException("写入失败"); } //}
[解决办法]
刚看到你信息,我测试了你8楼贴出来的代码,在我这工作正常,一次就能生成保存文件,且内容也正确。
所以你的问题现在是啥?
不过发现你一个小笔误:
save=new FileDialog(f,"关闭WoW",FileDialog.SAVE);