Basically I have a GUI that inherits from the JFrame class and has its own main method.
It gives the error
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)
Here is the source code
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();
}
}
I checked that all of my variables were declared properly. I am not sure what exactly is wrong. Could anyone who is more of an expert in debugging help?
Thanks!
Because
panelis null and you try to call some methods of it (panel.add(messageLabel1);), you need to initialize it: