基本上我有一个 GUI,它继承自 JFrame 类并有自己的 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();
}
}
我检查了我的所有变量是否已正确声明。我不确定到底出了什么问题。哪位更擅长调试的人可以提供帮助?
谢谢!
最佳答案
因为 panel
是 null 并且你试图调用它的一些方法 (panel.add(messageLabel1);
),你需要初始化它:
private JPanel panel = new JPanel();
关于java - 为什么我的 JFrame GUI 程序会出现运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8307405/