当前位置: 代码迷 >> J2SE >> 有关问题:Exception in thread "main" java.lang.NullPointerException
  详细解决方案

有关问题:Exception in thread "main" java.lang.NullPointerException

热度:60   发布时间:2016-04-24 14:49:01.0
求助问题:Exception in thread "main" java.lang.NullPointerException
出错祥细:
Exception   in   thread   "main "   java.lang.NullPointerException
at   awt.GridLayoutTest.init(GridLayoutTest.java:36)
at   awt.GridLayoutTest. <init> (GridLayoutTest.java:24)
at   awt.GridLayoutTest.main(GridLayoutTest.java:57)
程序如下:
package   awt;

import   java.awt.Button;
import   java.awt.Color;
import   java.awt.Frame;
import   java.awt.GridLayout;
import   java.awt.Panel;
import   java.awt.TextField;

public   class   GridLayoutTest   {
Frame   frame   =   null;
Panel   pn,pm,pc,ps;
String[]   s   =   { "7 ", "8 ", "9 ", "/ ",
"sprt ", "4 ", "5 ", "6 ",
"* ", "% ", "1 ", "2 ",
"3 ", "- ", "1/x ", "0 ",
"+/- ", ". ", "+ ", "= "};
String[]   m   =   { "MC ", "MR ", "MS ", "M+ "};
Button[]   bs   =   new   Button[s.length];
Button[]   bm   =   new   Button[m.length];
TextField   tf   =   new   TextField( "0. ",150);

public   GridLayoutTest()   {
init();
}

private   void   init()   {
frame   =   new   Frame( "计算器   v1.0 ");
frame.setLayout(new   GridLayout(4,5,3,3));
for(int   i=0;i <bs.length;i++)
{
bs[i]   =   new   Button(s[i]);
bs[i].setBackground(Color.LIGHT_GRAY);
bs[i].setForeground(Color.blue);

ps.add(bs[i]);
}
for(int   j=0;j <bm.length;j++){
bm[j]   =   new   Button(m[j]);
bm[j].setBackground(Color.LIGHT_GRAY);
bm[j].setForeground(Color.blue);

pm.add(bm[j]);
}
frame.add(pm, "West ");
frame.add(ps, "South ");
frame.setSize(150,150);
frame.pack();
frame.setVisible(true);

}

/**
  *   @param   args
  */
public   static   void   main(String[]   args)   {
new   GridLayoutTest();

}

}


------解决方案--------------------
ps没有初始化,就这样用了:ps.add(bs[i])。
new一个出来。
------解决方案--------------------
1楼正解
Panel pn,pm,pc,ps;这些最好全部初始化
  相关解决方案