简体   繁体   中英

NullPointerException when trying to get element from store

I have a swing application with the following classes:

ControllerGUI: loads my mainform
Date: used to convert numbers from input into date format
Employee: extends person class and sets variables like salary, job title
MainForm: swing gui
Person: sets variables for other details like name, gender, dob
Store: Holds the array Employee[] list;

I have a displayInformation JPanel where I want to display the name, salary, job title etc in JTextFields from the store and then allow the user to browse the entries with next and previous buttons. However I'm hitting a NullPointerException when trying to get it to work in the first place.

In my MainForm I add a new Store

Store testStore = new Store(100);

I want the elements in the array to be outputed to different JTextFields like:

showName.setText(testStore.list[listIndex].name);

(where listIndex is an int I initiated) but from that I am getting a NullPointerException, the error goes away if I take off the .name or .salary whatever I want to get, but then obviously there's no point in the code anyway.

Any help here would be greatly appreciated!

 public class Store implements Serializable {
    private static int MAXSIZE; // holds the size of the array
    private static int count; // keeps count of number of persons stored in
                                // array

    Employee[] list; // array for storing person objects

    public Store(int size) {
        list = new Employee[size];
        MAXSIZE = size;
        count = 0;
    }

This happens because:

testStore.list[listIndex]

is null.

You can use:

showName.setText(testStore.list[listIndex] == null ? null : testStore.list[listIndex].name);

Actually, a lot better approach is to use setters and getters in Person class, and then use:

testStore.list[listIndex].getName()

To get the Person's name.

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