簡體   English   中英

嘗試從存儲中獲取元素時發生NullPointerException

[英]NullPointerException when trying to get element from store

我有一個帶有以下課程的swing應用程序:

ControllerGUI:加載我的主窗體
日期:用於將數字從輸入轉換為日期格式
員工:擴展人員類別並設置變量,如薪水,職稱
MainForm:swing gui
人員:為其他詳細信息設置變量,例如姓名,性別,出生日期
Store:保存數組Employee []列表;

我有一個displayInformation JPanel,我想在其中顯示商店中JTextFields中的名稱,薪水,職位等,然后允許用戶使用上一個和下一個按鈕瀏覽條目。 但是,我試圖首先使NullPointerException起作用。

在我的MainForm中,添加一個新商店

Store testStore = new Store(100);

我希望將數組中的元素輸出到不同的JTextField,例如:

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

(其中listIndex是我啟動的int),但是從中得到NullPointerException,如果我刪除想要獲取的.name或.salary,錯誤就會消失,但是顯然代碼中沒有任何意義。

在這里的任何幫助將不勝感激!

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

發生這種情況是因為:

testStore.list[listIndex]

一片空白。

您可以使用:

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

實際上,更好的方法是在Person類中使用setter和getter,然后使用:

testStore.list[listIndex].getName()

獲得此人的名字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM