Frage

Grundsätzlich habe ich eine GUI, die von der JFRame -Klasse erbt und ihre eigene hat hauptsächlich Methode.

Es gibt den Fehler

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)

Hier ist der Quellcode

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();
    }
}

Ich habe überprüft, ob alle meine Variablen ordnungsgemäß deklariert wurden. Ich bin mir nicht sicher, was genau falsch ist. Könnte jemand, der eher ein Experte für die Debugging -Hilfe ist?

Vielen Dank!

War es hilfreich?

Lösung

Da panel ist null und Sie versuchen, einige Methoden davon anzurufen (panel.add(messageLabel1);), Sie müssen es initialisieren:

private JPanel panel = new JPanel();

Andere Tipps

Du fehlst

  panel = new JPanel();

in Ihrem Build -Panel -Code. Darüber hinaus müssen Sie sein Layout ändern, um mehrere Elemente hinzuzufügen.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top