日期:2014-05-20  浏览次数:20866 次

代码问题???
大家帮忙看一下 为什么编译通过了 运行时却报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("接收程序");

}
}


------解决方案--------------------
getMenuBar返回对象为空
------解决方案--------------------
Java code

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

@SuppressWarnings("serial")
public class MyFrame extends Frame {
    [color=#FF0000]private MenuBar mb = new MenuBar();[/color]
    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);
        [color=#FF0000]//mb = getMenuBar();[/color]
        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("接收程序");

    }
}