本帖最后由 田建 于 2012-6-8 06:58 编辑
这是我在编写记事本小程序的时候遇到的一个小问题,为什么在frame中设置文本区域没有效果,不论设不设置流式布局都是一样,然而把流式布局和文本区域的设置都去掉,采用默认布局又可以了,为什么?- @author田建
- @version v1.1
- */
- import java.awt.*;
- import java.awt.event.*;
- import java.io.*;
- class MyMenuDemo
- {
- private Frame f;
- private TextArea ta;
- private MenuBar mb;
- private Menu me;
- private MenuItem miNew,miSave,miLoad;
- private File file;
-
- private FileDialog openDia,saveDia;
-
- MyMenuDemo()
- {
- init();
- }
-
-
- public void init()
- {
- f=new Frame("田建--记事本");
- f.setBounds(300,100,650,600);
- ta=new TextArea();
- //ta.setBounds(302,105,400,300);
- //f.setLayout(new FlowLayout());//为什么设置成了流式布局之后再设置文本区域没有效果
-
- mb=new MenuBar();
- me=new Menu("文件(F)");
- miNew=new MenuItem("新建");
- miSave=new MenuItem("保存(S)");
- miLoad=new MenuItem("打开(O)");
-
- mb.add(me);
- me.add(miNew);
-
- me.add(miLoad);
- me.add(miSave);
- f.setMenuBar(mb);
- f.add(ta);
-
- openDia=new FileDialog(f,"打开文件",FileDialog.LOAD);
- saveDia=new FileDialog(f,"保存文件",FileDialog.SAVE);
-
- myEvent();
- f.setVisible(true);
-
- }
-
- public void myEvent()
- {
- f.addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- System.exit(0);
- }
- });
- miLoad.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 ex)
- {
- throw new RuntimeException("读取失败");
- }
- }
- });
- miSave.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("");
- }
- }
- });
-
- }
-
- public static void main(String[] args)
- {
- new MyMenuDemo();
- }
-
- }
复制代码 |