Obtain the background color of the JButton problem

advertisements

I've this class:

public class Gemme extends JButton implements ActionListener{

    private static int indicateur=0;
    private Gemme gemme1;
    private Gemme gemme2;

    @Override
    public void actionPerformed(ActionEvent e) {
        indicateur = 1-indicateur;

        if(this.indicateur==1)//first click
        {
            this.gemme1 = (Gemme) e.getSource();

        }
        else
        {
            this.gemme2 = (Gemme) e.getSource();
            switchColor();
        }

    }

    private void switchColor()
    {
       Color c = gemme1.getBackground();
       gemme1.setBackground(gemme2.getBackground());
       gemme1.setBackground(c);
       System.out.println("color switched");
    }

Basically i'm creating a game: A grid of Colored JButtons, when the player try to click on two JBs in order to switch color between them.

The problem that i get NPE at this line:

Color c = gemme1.getBackground();

But when i put the Color c = gemme1.getBackground(); in the actionPerformed like that:

 public void actionPerformed(ActionEvent e) {
            indicateur = 1-indicateur;

            if(this.indicateur==1)//first click
            {
                this.gemme1 = (Gemme) e.getSource();
                Color c = gemme1.getBackground();

            }
            else
            {
                this.gemme2 = (Gemme) e.getSource();
                //switchColor();
            }

        }

It works, i didn't understand, is the JB is losing his properties when the action is not matching to it?

Any explanation please?

EDIT I changed switchColor() to :

   private void switchColor()
    {
        System.out.println(gemme1);
        System.out.println(gemme2);
    }

Output:

null
mini.projet.dev.game.components.Gemme[btn42,104,216,51x53,alignmentX=0.0,alignmentY=0.5,b...........

How gemme1 becomes null ?


I solved the problem, it was just changing gemme1/gemme2 to static in order to becomes shared between other instances of Gemme:

private static Gemme gemme1;
private static Gemme gemme2;