import java.io.*;
import java.awt.*;
import java.awt.event.*;
public class Text2 {//一个打开文件的窗口及文件对话框
public static void main(String args[])
{
new Menulei();
}
}
class Menulei{
private Frame fr;
private TextArea wenben;
private FileDialog fd;
private MenuBar mb;
private Menu zhucaidan;
private MenuItem dakai,baocun,tuichu;
Menulei()
{
inti();
}
public void inti()
{
fr=new Frame();
fr.setBounds(250,200,600,500);
mb=new MenuBar();
zhucaidan=new Menu("文件");
dakai=new MenuItem("打开");
baocun=new MenuItem("保存");
tuichu=new MenuItem("退出");
mb.add(zhucaidan);
zhucaidan.add(dakai);
zhucaidan.add(baocun);
zhucaidan.add(tuichu);
wenben=new TextArea();
fd=new FileDialog(fr,"我的打开",FileDialog.LOAD );
fd.setBounds(200,100,500,400);
fr.add(wenben);
fr.setMenuBar(mb);
myevent();
fr.setVisible(true);
}
public void myevent()
{ dakai.addActionListener(new ActionListener() //给打开菜单添加监听器(匿名内部类形式)
{
public void actionPerformed(ActionEvent e)
{
fd.setVisible(true);
String mulu=fd.getDirectory();
String name=fd.getFile();
if(mulu==null||name==null)
return;
wenben.setText("");
File file=new File(mulu,name);
try{
BufferedReader br=new BufferedReader(new FileReader(file));
String str=null;
while((str=br.readLine())!=null)
{
wenben.append(str+"\r\n");
}
br.close();
}
catch(IOException e1)
{
throw new RuntimeException("读取失败");
}
}
});
fr.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
tuichu.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
当菜单里面的打开菜单被鼠标单击后为什么打开监听器里面的代码没有全部执行而是等选择了文件之后才执行完?当事件被触发时监听器里面的处理代码不是都会执行完吗?
} |
|