Search code examples
javaarraysswingjlistlistselectionlistener

ListSelectionListener null pointer error


I'm trying to get a specific color for a specific category display on my south JPanel but I get NullPointerExeception error. What am I doing wrong?

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

Solution

  • Try checking if the selected index in your list is greater than -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 means that no item in your list is selected. If your error occurs on the if statement, then kategorLista is null and needs to be initialized. Your sample code, you provided, looks like you initialized it. Otherwise, syd is null and needs to be initialized.

    If all of that is running. Then in the code that you provided.

    öst.add(kategoriLista);
    

    Is öst initialized? The error you're getting should have been pointing at the line of code that is causing the error.

    EDIT

    Based on the extra code that you've added... Make these two lines of codes class variables

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

    You have them coded in the contructor and they cannot be seen anywhere else in the class. If you already have them declared as class variables, then in your constructor change the code to:

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

    I believe the name is call shadowing... You original code, shadowed your class variables, and local variables were initialized instead of your class variables.