我正在尝试为我的南JPanel上的特定类别显示获取特定颜色,但是我收到NullPointerExeception错误。我做错了什么?
//This is the arrays holding the category names and colors.
答案 0 :(得分:2)
尝试检查列表中所选索引是否大于-1。
//This is the arrays holding the category names and colors.
String[] cati = {"Ingen", "Matställen", "Skolor", "Kyrkor", "Kollektiv trafik"};
Color[] colors = {Color.WHITE, Color.BLUE, Color.GREEN, Color.YELLOW, Color.PINK};
// This is a inner class in the super class.
class kategoriFärg implements ListSelectionListener {
public void valueChanged(ListSelectionEvent event) {
if (kategorLista.getSelectedIndex() > -1) {
System.out.println("does this work?");
syd.setBackground(colors[kategoriLista.getSelectedIndex()]);
//syd is the south JPanel
}
}
}
-1表示未选择列表中的项目。如果在if语句中发生错误,则kategorLista为null,需要初始化。您提供的示例代码看起来像是初始化它。否则,syd为null,需要初始化。
如果所有这些都在运行。然后在您提供的代码中。
öst.add(kategoriLista);
öst
是否已初始化?您遇到的错误应该指向导致错误的代码行。
根据您添加的额外代码...制作这两行代码类变量
String[] cati = { "Ingen", "Matställen", "Skolor", "Kyrkor",
"Kollektiv trafik" };
Color[] colors = { Color.WHITE, Color.BLUE, Color.GREEN, Color.YELLOW,
Color.PINK };
你在构造函数中编写了它们,并且在类中的任何其他地方都看不到它们。如果已经将它们声明为类变量,那么在构造函数中将代码更改为:
cati = { "Ingen", "Matställen", "Skolor", "Kyrkor",
"Kollektiv trafik" };
colors = { Color.WHITE, Color.BLUE, Color.GREEN, Color.YELLOW,
Color.PINK };
我相信名称是调用阴影...你原始代码,阴影你的类变量,局部变量被初始化而不是你的类变量。