有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java ListSelectionListener空指针错误

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

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

共 (1) 个答案

  1. # 1 楼答案

    尝试检查列表中选定的索引是否大于-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 };
    

    我相信这个名字叫阴影。。。您可以使用原始代码,隐藏类变量,并初始化局部变量而不是类变量