添加动作时的Java.lang.NullPointerException按钮的监听器?

时间:2014-01-31 03:49:45

标签: java nullpointerexception

以前从未在此发布,但我不确定为什么它不使用此代码但在另一个工作。哦,在使用BlueJ时,它说calcButton.addActionListener(handler);是错误。

public class JoesAutoGUI extends JPanel
{
protected RoutineService routineServices;
protected NonroutineService nonroutineServices;
protected SummaryPanel summarypanel;

protected JTabbedPane tabbs;

protected JPanel title;
protected JPanel charges;
protected JPanel summary;
protected JPanel buttonPanel;

protected JLabel titlePanel;

protected JButton calcButton;
protected JButton exitButton;

protected ImageIcon car;


public JoesAutoGUI()
{
    //setLayout(new BorderLayout());
    tabbs = new JTabbedPane(JTabbedPane.TOP);

    buildButtonPanel();
    buildTitlePanel();

    JPanel charges = new JPanel(); 
    tabbs.addTab("Charges", null, charges, "Charges calculator");
    charges.setLayout(new BorderLayout() );
    charges.add(titlePanel,                                   BorderLayout.NORTH);  
    charges.add( routineServices = new RoutineService(),      BorderLayout.WEST);
    charges.add(nonroutineServices = new NonroutineService(), BorderLayout.SOUTH);
    charges.add(buttonPanel,                                  BorderLayout.EAST);

    JPanel summary = new JPanel();
    tabbs.addTab("Summary", null, summary,"sum summary");
    summary.setLayout(new BorderLayout() );
    summary.add(summarypanel = new SummaryPanel(), BorderLayout.CENTER);

   add(tabbs);
}


private void buildButtonPanel()
{
    buttonPanel = new JPanel();

    setLayout(new GridLayout(5,1));

    JoesAutoHandler handler = new JoesAutoHandler(this);
    calcButton.addActionListener(handler); <-------error here?
    exitButton.addActionListener(handler);

    buttonPanel.add(new JLabel(""));
    buttonPanel.add(new JLabel(""));
    buttonPanel.add(new JButton("Calculate Charges"));
    buttonPanel.add(new JButton("Exit"));
    buttonPanel.add(new JLabel(""));
}

private void buildTitlePanel()
{
    //build the label
    titlePanel = new JLabel();

    //set the layout for label
    setLayout(new FlowLayout());

    //create the icon
    car = new ImageIcon("images/car.jpg");

    //choose the the lable and icon used in the label
    titlePanel = new JLabel("Joe's Automotives", car, JLabel.CENTER );

    //add the titel panel
    add(titlePanel);
}
}

不确定是否有人可以在没有其余代码的情况下提供帮助?

1 个答案:

答案 0 :(得分:5)

您必须创建JButton的对象,例如JButton calcButton =new JButton();

在这一行protected JButton calcButton;中你刚刚创建了一个引用,但你没有在任何地方创建对象