import java.awt.*;
import java.awt.event.*;
import java.io.*;
class myMenuDemo
{
private Frame f;
private TextArea ta;
private MenuBar mb;
private Menu m,subMenu;
private MenuItem subItem,openItem,saveItem,closeItem;
private FileDialog openDia,saveDia;
myMenuDemo()
{
init();
}
public void init()
{
f=new Frame("my frame");
f.setBounds(300,100,500,400);
//f.setLayout(new FlowLayout());
//不设置布局则为边界布局,TextArea则和窗体一样大小了。
mb=new MenuBar();
m=new Menu("文件");
subMenu=new Menu("子菜单");
subItem=new MenuItem("子项");
openItem=new MenuItem("打开");
saveItem=new MenuItem("保存");
closeItem=new MenuItem("关闭");
subMenu.add(subItem);
m.add(subMenu);
m.add(openItem);
m.add(closeItem);
mb.add(m);
f.setMenuBar(mb);
f.add(ta);
openDia=new FileDialog(f,"my open",FileDialog.LOAD);
saveDia=new FileDialog(f,"my save",FileDialog.SAVE);
myEvent();
f.setVisible(true);
}
public void myEvent()
{
f.addWindowListener(new WindowAdapter()
{
public void windowCloing(WindowEvent e)
{
System.exit(0);
}
});
openItem.addActionListener(new ActionListener()//打开文件事件处理
{
public void actionPerformed(ActionEvent e)
{
openDia.setVisible(true);//打开对话框显示出来
String dirPath=openDia.getDirectory();//Dialog中的方法getDirectory获取文件路径
String fileName=openDia.getFile();//Dialog中的方法getFile获取文件名
if(dirPath==null || fileName==null)
return; //为null时返回
ta.setText("");//清空文本区
File file=new File(dirPath,fileName);//路径和文件名封装
try
{
BufferedReader bufr=new BufferedReader(new FileReader(file));//读入file
String line=null;
while( (line=bufr.readLine())!=null )//读取一行不为null,则
{
ta.append(line+"\r\n"); //该行就写入文本区,并回车
}
}
catch (IOException ioe)//异常处理:抛出
{
throw new RuntimeException("读取文件失败");
}
}
});
saveItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
closeItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args)
{
new myMenuDemo();
}
}
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Container.java:1041)
at java.awt.Container.add(Container.java:365)
at myMenuDemo.init(myMenuDemo.java:47)
at myMenuDemo.<init>(myMenuDemo.java:19)
at myMenuDemo.main(myMenuDemo.java:115) |