使用JLabel数组获取NullPointerException [duplicate]

时间:2021-07-20 17:04:04

This question already has an answer here:

这个问题在这里已有答案:

I have searched for an answer and found none. I have declared a JLabel array inside a class to be able to edit its text from another class:

我找了一个答案但没找到。我在类中声明了一个JLabel数组,以便能够从另一个类编辑它的文本:

public static JLabel[] portion = new JLabel[11];

And I set its initial text just before adding these labels to a panel:

我在将这些标签添加到面板之前设置了初始文本:

for(int i = 0; i < 11; i++){
        portion[i].setText("0.00%");
    }

When I try to compile my code to test what I have so far, I get a NullPointerException, and Eclipse points to my line of code:

当我尝试编译我的代码来测试到目前为止我得到的东西时,我得到一个NullPointerException,Eclipse指向我的代码行:

portion[i].setText("0.00%");

Any advise is appreciated.

任何建议表示赞赏。

2 个解决方案

#1


4  

You have created an array, you now need to populate the array; current it is an array with 11 nulls

你已经创建了一个数组,现在需要填充数组;当前它是一个包含11个空值的数组

for(int i = 0; i < 11; i++) {
    portion[i] = new JLabel();
    portion[i].setText("0.00%");
}

or simply

for(int i = 0; i < 11; i++) {
    portion[i] = new JLabel("0.00%");
}

#2


0  

public static JLabel[] portion = new JLabel[11];

is just like creating array of nulls, meaning array portion array is empty.

就像创建空数组一样,意味着数组部分数组为空。

You should now iterate it through and populate the array with actual JLable objects.

您现在应该迭代它并使用实际的JLable对象填充数组。

And then try assigning values through setText method.

然后尝试通过setText方法分配值。

#1


4  

You have created an array, you now need to populate the array; current it is an array with 11 nulls

你已经创建了一个数组,现在需要填充数组;当前它是一个包含11个空值的数组

for(int i = 0; i < 11; i++) {
    portion[i] = new JLabel();
    portion[i].setText("0.00%");
}

or simply

for(int i = 0; i < 11; i++) {
    portion[i] = new JLabel("0.00%");
}

#2


0  

public static JLabel[] portion = new JLabel[11];

is just like creating array of nulls, meaning array portion array is empty.

就像创建空数组一样,意味着数组部分数组为空。

You should now iterate it through and populate the array with actual JLable objects.

您现在应该迭代它并使用实际的JLable对象填充数组。

And then try assigning values through setText method.

然后尝试通过setText方法分配值。