为什么我的JFrame GUI程序会出现运行时错误?

时间:2011-11-29 07:48:19

标签: java swing jframe actionlistener joptionpane

基本上我有一个继承自JFrame类的GUI,并且有自己的 main 方法。

它给出错误

Exception in thread "main" java.lang.NullPointerException
    at MilesPerGallonApp.buildPanel(MilesPerGallonApp.java:33)
    at MilesPerGallonApp.<init>(MilesPerGallonApp.java:20)
    at MilesPerGallonApp.main(MilesPerGallonApp.java:58)

这是源代码

import javax.swing.*;
import java.awt.event.*;

public class MilesPerGallonApp extends JFrame
{
    private JPanel panel;
    private JLabel messageLabel1;
    private JLabel messageLabel2;
    private JTextField distanceTextField;
    private JTextField gallonTextField;
    private JButton calcButton;
    private final int WINDOW_WIDTH = 500;
    private final int WINDOW_HEIGHT = 280;

    public MilesPerGallonApp()
    {
        super("Fuel Economy Calculator");
        setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        buildPanel();
        add(panel);
        setVisible(true);
    }

    private void buildPanel()
    {
        messageLabel1 = new JLabel("Enter maximum distance.");
        messageLabel2 = new JLabel("Enter tank capacity.");
        distanceTextField = new JTextField(8);
        gallonTextField = new JTextField(4);
        calcButton =  new JButton("Calculate MPG");

        panel.add(messageLabel1);
        panel.add(messageLabel2);
        panel.add(distanceTextField);
        panel.add(calcButton);
    }

    private class CalcButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            String gallonString;
            String milesString;
            double MPG;

            gallonString = gallonTextField.getText();
            milesString = distanceTextField.getText();

            MPG = Double.parseDouble(milesString) / Double.parseDouble(gallonString);

            JOptionPane.showMessageDialog(null, "The fuel economy is " + MPG + " miles per gallon.");
        }
    }

    public static void main(String[] args)
    {
        new MilesPerGallonApp();
    }
}

我检查了所有变量都被正确声明了。我不确定到底出了什么问题。任何更喜欢调试专家的人都可以帮忙吗?

谢谢!

2 个答案:

答案 0 :(得分:7)

因为panel为null并且您尝试调用它的某些方法(panel.add(messageLabel1);),所以需要对其进行初始化:

private JPanel panel = new JPanel();

答案 1 :(得分:3)

你错过了

  panel = new JPanel();

在您的构建面板代码中。此外,您需要更改其布局以添加多个元素。