2010-11-25 54 views
1

//Customer.java我應該如何解決這種錯誤的

import javax.swing.*; 
public class Customer 
{ 
//variables for from window 

static JFrame frameObj; 
static JPanel panelObj; 

// variables for labels 

JLabel labelCustomerName; 
JLabel labelCustomerCellNo; 
JLabel labelCustomerPackage; 
JLabel labelCustomerAge; 

// Variables for data entry controls 

JTextField textCustomerName; 
JTextField textCustomerCellNo; 
JComboBox comboCustomerPackage; 
JTextField textCustomerAge; 

public static void main(String args[]) 
    { 
     Customer CustObj = new Customer(); 
    } 

public Customer() 
    { 

      ///Add the appropriate controls to the frame in the construcor 
      ///Create Panel 
      panelObj= new JPanel(); 
      frameObj.getContentPane().add(panelObj); 

      ///Setting close button 
      frameObj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

      ///Create and add the appropriate controls 

      ///Initializing the labels 

      labelCustomerName = new JLabel("Customer Name: "); 
      labelCustomerCellNo = new JLabel("Cell Number: "); 
      labelCustomerPackage = new JLabel("Package: "); 
      labelCustomerAge = new JLabel("Age: "); 

      ///NIintialzing the data entry Controls 
      textCustomerName = new JTextField(30); 
      textCustomerCellNo = new JTextField(15); 
      textCustomerAge = new JTextField(2);  
      String packages[] = { "Executive" , "Standard"}; 
      comboCustomerPackage = new JComboBox(packages); 

      ///Adding Controls to the Customer Name 
      panelObj.add(labelCustomerName); 
      panelObj.add(textCustomerName); 

      ///Adding Controls to the Customer Cell Number 
      panelObj.add(labelCustomerCellNo); 
      panelObj.add(textCustomerCellNo); 

      ///Adding Controls to the Customer Age 
      panelObj.add(labelCustomerAge); 
      panelObj.add(textCustomerAge); 

      ///Adding Controls to the Customer Package 
      panelObj.add(labelCustomerPackage); 
      panelObj.add(comboCustomerPackage); 

    } 

} 

//當我執行這個程序,我得到它說

exception in thread "main" java.lang.NullPointerException 
at Customer.<init>(Customer.java:35) 
at Customer.<init>(Customer.java:26) 

回答

2

frameObj尚未初始化錯誤/分配給,所以它是NULL。打電話給它getContentPane()會給你一個NullPointerException

3

的問題是在這條線:

frameObj.getContentPane().add(panelObj); 

看看frameObj是如何定義的:

static JFrame frameObj; 

它從來沒有真正得到初始化。當您嘗試獲取其內容窗格時,它仍然爲空。這就是Nul​​lPointerException的意思 - 你試圖在一個null對象上運行一個方法。

嘗試改變frameObj調用此:

static JFrame frameObj = new JFrame(); 

這應該解決這個問題。