2011-11-29 61 views
1

基本上我有一個從JFrame類繼承的GUI,並有自己的主要的方法。爲什麼我的JFrame GUI程序會給出運行時錯誤?

它給人的錯誤

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

我檢查我所有的變量都正確聲明。我不確定究竟是什麼錯誤。任何人誰是更多的調試專家幫助?

謝謝!

+0

你在什麼時間得到NullPointerException? – gprathour

回答

7

因爲panel爲空並嘗試調用它(panel.add(messageLabel1);)一些方法,你需要將其初始化:

private JPanel panel = new JPanel(); 
3

您在構建面板代碼所缺少

panel = new JPanel(); 

。此外,您需要更改其佈局以添加多個元素。

相關問題