当前位置: 代码迷 >> J2SE >> 代码有关问题?
  详细解决方案

代码有关问题?

热度:86   发布时间:2016-04-24 01:48:15.0
代码问题???
大家帮忙看一下 为什么编译通过了 运行时却报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("接收程序");    }}
  相关解决方案