Question

I'm having this strange problem with my code, I've made a array of labels so that when I pass the array to another class this one can read and know the position of the label I want to move and change it's position, I've tried with prints all over the place to know what the array is passing, before passing the array to the other class I placed a print, the print in that moment has the correct information but when I tell the button to call the method from my other class and passes it, I get a NullPointerException.

That's how I make the array

JLabel[] listabolaslabels ;


    Partida partida;


    public Gui() {
        initComponents();
        //partida = new Partida();
        setLocationRelativeTo(null);
        setResizable( false );



        this.listabolaslabels = new JLabel[]{

            //Bolas Nivel 1, Jugador 1
            this.bolaj1,
            this.nivel1j1bola1,
            this.nivel1j1bola2,
            this.nivel1j1bola3,
            //Bolas Nivel 2, Jugador 1
            this.nivel2j1bola1,
            this.nivel2j1bola2,
            this.nivel2j1bola3,
            //Bolas Nivel 3, Jugador 1
            this.nivel3j1bola1,
            this.nivel3j1bola2,
            this.nivel1j1bola3,


            //Bola Comodin
            this.labelcomodin,


            //Bolas Nivel 1, Jugador 2
             this.nivel1j2bola1,
            this.nivel1j2bola2,
            this.nivel1j2bola3,
            //Bolas Nivel 2, Jugador 2
            this.nivel2j2bola1,
            this.nivel2j2bola2,
            this.nivel2j2bola3,
            //Bolas Nivel 3, Jugador 12
            this.nivel3j2bola1,
            this.nivel3j2bola2,
            this.nivel3j2bola3};

    }

There is the code that the button executes

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        System.out.println(listabolaslabels[0]);

When the program get's to this point it shows the nullpointerexception
        partida.getlista(listabolaslabels[0]);

    } 

Meanwhile in the other class, in this case "Partida"

public void getlista(JLabel lista){
        //System.out.println(lista);
    }

That's the method, I'm using to test

Was it helpful?

Solution

I believe you have misidentified the source of your error. You declare the field partida but do not initialize it anywhere. This field is initialized to null by default.

Make sure that partida is not null before attempting to call its getlista() method, or you will get an NPE.

You haven't shown all your code so it may be the case that you do set partida to something somewhere, but you should verify that it is actually not null at the point where you are getting the NPE.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top