简体   繁体   中英

NullPointerException in JFrame

I have a class Catalogue to store info about it. Here i had just use two methods:

public void setCataName(String n)
    {cataName = n;}

public String getCataName()
    {return cataName;}

This is the code for my JFrame:

public class AddCataFrame extends JFrame
{
    JLabel lname; 
    JTextField tname;
    Catalogue catalogue;

    AddCataFrame()
    {
        super("Add New Catalogue");
        setLayout(new FlowLayout());

        lname = new JLabel("Name:", SwingConstants.LEFT);

        tname = new JTextField(15);

        textListener t = new textListener();
        tname.addActionListener(t);

        add(lname);
        add(tname);
    }

    class textListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {   
            //get the name from the textField after entered by user
            //then set it to the name of catalogue.
            //This is the place give me NullPointerException error.
            catalogue.setCataName(tname.getText()); 

            JOptionPane.showMessageDialog(null,catalogue.getCataName());
        }
    }
}

I cannot figure it out why give me a NullPointerException. Please help me.

Where do you initialize your catalogue variable? You don't. Solution: initialize it first before trying to use it.

eg,

This only declares the variable:

Catalogue catalogue;

This declares and initializes it:

Catalogue catalogue = new Catalogue();

or this can initialize the variable if you want to use a Catalogue object passed into your class on creation:

AddCataFrame(Catalgogue catalogue)
{
    super("Add New Catalogue");
    this.catalogue = catalogue; // *************

    setLayout(new FlowLayout());

    lname = new JLabel("Name:", SwingConstants.LEFT);

    tname = new JTextField(15);

    textListener t = new textListener();
    tname.addActionListener(t);

    add(lname);
    add(tname);
}

More importantly, you need to learn the general concepts of how to debug a NPE (NullPointerException). You should inspect the line carefully that throws it, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me.

Your variable catalogue is defined but never initialized. That's why you get the exception.

You should have a line like catalogue = new Catalogue()

You didn't initialise catalogue . You should change

Catalogue catalogue;

to

Catalogue catalogue = new Catalogue();

Non-primitive fields are by default initialised to null , hence the NullPointerException on line

catalogue.setCataName(tname.getText());

您必须初始化目录

Cataloge  catalog= new Cataloge();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM