我应该如何解决这类错误

时间:2010-11-25 06:31:05

标签: java exception exception-handling error-handling

// 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 个答案:

答案 0 :(得分:3)

问题出在这一行:

frameObj.getContentPane().add(panelObj);

看一下frameObj的定义方式:

static JFrame frameObj;

它实际上从未被初始化。当您尝试获取其内容窗格时,它仍为null。这就是Nul​​lPointerException的意思 - 你试图在一个null的对象上运行一个方法。

尝试将frameObj调用更改为:

static JFrame frameObj = new JFrame();

这应解决问题。

答案 1 :(得分:2)

frameObj尚未初始化/分配,因此它是NULL。调用getContentPane()会给你一个NullPointerException