
编译时出现这个异常,如何解决Exception in thread "main" java.lang.NullPointerException
现源程序如下:importjava.awt.*;importjavax.swing.*;importjava.awt.event.*;publicclassMyCalcu...
现源程序如下:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MyCalculate extends JFrame implements ActionListener{
private TextField result;
private JButton button[];
public MyCalculate()
{
super("简单计算器");
this.setBounds(400,200,300,200);
this.setBackground(Color.LIGHT_GRAY);
this.setLayout(new BorderLayout());
result=new TextField();
this.add(result,"North");
Panel panel=new Panel();
panel.setLayout(new GridLayout(4,4,4,4));
this.add(panel,"Center");
String str[]={"7","8","9","/","4","5","6","*","1","2","3","-","0",".","=","+"};
button=new JButton[str.length];
for(int i=0;i<str.length;i++)
{
button[i].setName(str[i]);
panel.add(button[i]);
button[i].addActionListener(this);
}
this.setVisible(true);
}
public static void main(String[] args) {
new MyCalculate();
}
public void actionPerformed(ActionEvent e) {
}
}
出现异常的地方应该为这条语句:button[i].setName(str[i]);我申明了button[],并且也new了空间给它,就是不清楚到底问题出在哪 展开
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MyCalculate extends JFrame implements ActionListener{
private TextField result;
private JButton button[];
public MyCalculate()
{
super("简单计算器");
this.setBounds(400,200,300,200);
this.setBackground(Color.LIGHT_GRAY);
this.setLayout(new BorderLayout());
result=new TextField();
this.add(result,"North");
Panel panel=new Panel();
panel.setLayout(new GridLayout(4,4,4,4));
this.add(panel,"Center");
String str[]={"7","8","9","/","4","5","6","*","1","2","3","-","0",".","=","+"};
button=new JButton[str.length];
for(int i=0;i<str.length;i++)
{
button[i].setName(str[i]);
panel.add(button[i]);
button[i].addActionListener(this);
}
this.setVisible(true);
}
public static void main(String[] args) {
new MyCalculate();
}
public void actionPerformed(ActionEvent e) {
}
}
出现异常的地方应该为这条语句:button[i].setName(str[i]);我申明了button[],并且也new了空间给它,就是不清楚到底问题出在哪 展开
1个回答
展开全部
这是空指针异常,你检查下哪里你设置为空了,或者用syso打印下一些变量时否是空的,如果为空了,或者传值,或者赋值 打印你的那些值,看哪个是空的?或者dibug跟一下
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询