ListSelectionListener 空指针错误

ListSelectionListener null pointer error

我试图为我的南 JPanel 上的特定类别显示获取特定颜色,但我收到 NullPointerExeception 错误。我做错了什么?

//This is the arrays holding the category names and colors.

尝试检查列表中所选的索引是否大于 -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初始化了吗?您收到的错误应该指向导致错误的代码行。

编辑

根据您添加的额外代码...将这两行代码设为 class 变量

String[] cati = { "Ingen", "Matställen", "Skolor", "Kyrkor",
        "Kollektiv trafik" };
Color[] colors = { Color.WHITE, Color.BLUE, Color.GREEN, Color.YELLOW,
        Color.PINK };

您已将它们编码在构造函数中,并且在 class 的其他任何地方都看不到它们。如果您已经将它们声明为 class 变量,那么在您的构造函数中将代码更改为:

cati = { "Ingen", "Matställen", "Skolor", "Kyrkor",
        "Kollektiv trafik" };
colors = { Color.WHITE, Color.BLUE, Color.GREEN, Color.YELLOW,
        Color.PINK };

我相信这个名字是调用隐藏...你的原始代码,隐藏了你的 class 变量,局部变量被初始化而不是你的 class 变量。