大家帮忙看一下 为什么编译通过了 运行时却报Exception in thread "main" java.lang.NullPointerException异常???import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyFrame extends Frame
{
private MenuBar mb;
private Menu mt1,mt2,mt3,mt4;
private MenuItem m;
MyFrame(String name){
super(name);
init();
}
 public void init()
{

setLayout(new FlowLayout());
setBounds(100,100,400,300);
mb = getMenuBar();
mt1= new Menu("文件");
mt2 = new Menu("编辑");
mt3 = new Menu("帮助");
mt4 = new Menu("点击");
m = new MenuItem("运算");
mt4.add(m);
mb.add(mt1);
mb.add(mt2);
mb.add(mt3);
mb.add(mt4);
this.setMenuBar(mb);
this.setVisible(true);
}
public static void main(String args[])
{
new MyFrame("接收程序");

}
}

解决方案 »

  1.   

    MenuBar java.awt.Frame.getMenuBar()
    Gets the menu bar for this frame.Returns:
    the menu bar for this frame, or null if this frame doesn't have a menu bar.
      

  2.   


    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;@SuppressWarnings("serial")
    public class MyFrame extends Frame {
    private MenuBar mb = new MenuBar();
    private Menu mt1, mt2, mt3, mt4;
    private MenuItem m; MyFrame(String name) {
    super(name);
    init();
    } public void init() {
    setLayout(new FlowLayout());
    setBounds(100, 100, 400, 300);
    //mb = getMenuBar();
    mt1 = new Menu("文件");
    mt2 = new Menu("编辑");
    mt3 = new Menu("帮助");
    mt4 = new Menu("点击");
    m = new MenuItem("运算");
    mt4.add(m);
    mb.add(mt1);
    mb.add(mt2);
    mb.add(mt3);
    mb.add(mt4);
    this.setMenuBar(mb);
    this.setVisible(true);
    } public static void main(String args[]) {
    new MyFrame("接收程序"); }
    }
      

  3.   

    mb = getMenuBar()改为mb = new MenuBar()。因为getMenuBar方法是用来获取当前frame里的MenuBar的,而当前frame并没有MenuBar,所以mb为空,出现空指针异常。
      

  4.   

    8楼的话我没太看懂 什么叫“当前frame并没有MenuBar”我继承了Frame不是就应该有MenuBar()方法吗?
    情节是详细点