当前位置: 代码迷 >> Java相关 >> 初学者~关于内部类的有关问题
  详细解决方案

初学者~关于内部类的有关问题

热度:5024   发布时间:2013-02-25 21:48:10.0
菜鸟求助~关于内部类的问题~
弄了两个按钮,改背景颜色,监听器写成内部类,可是总告诉我是空指针异常,本人刚开始学习,望前辈们多多帮忙,谢谢了。
代码如下:
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(); // 这句话惹得祸,楼主自己想想看
  相关解决方案