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

菜鸟求助~关于内部类的问题~
弄了两个按钮,改背景颜色,监听器写成内部类,可是总告诉我是空指针异常,本人刚开始学习,望前辈们多多帮忙,谢谢了。
代码如下:
public class ButtonTest extends JFrame {
private JPanel btp ;
public ButtonTest()
{
setTitle("ButtonTest");
setBounds(50,50,300,300);
JPanel btp = new JPanel();
JButton blueButton = new JButton("blue");
JButton redButton = new JButton("red");
btp.add(blueButton);
btp.add(redButton);
this.add(btp);
ColorAction blueAction = new ColorAction(Color.blue);
ColorAction redAction = new ColorAction(Color.red);
blueButton.addActionListener(blueAction);
  redButton.addActionListener(redAction);
}
private class ColorAction implements ActionListener
{
private Color backgroundColor;
public ColorAction(Color c)
{
backgroundColor = c;
}
public void actionPerformed(ActionEvent e)
{
btp.setBackground(backgroundColor);//就这行总是提示说空指针异常
}
}
}

错误信息:
  Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at ButtonTest$ColorAction.actionPerformed(ButtonTest.java:33)

------解决方案--------------------
backgroundColor 这个为空?
------解决方案--------------------
public ButtonTest()
{
setTitle("ButtonTest");
setBounds(50,50,300,300);
JPanel btp = new JPanel(); // 这句话惹得祸,楼主自己想想看