Search code examples
javaswingnullpointerexceptionjbutton

How to use the buttons outside the constructor?


I'm trying to create a slide puzzle in java. I created an array of 9 buttons (3x3) in the constructor. Now i want the buttons to either slide (swap positions with the empty text button), or i'll just swap the texts. But with the current code, I'm getting a Null Pointer Exception at run-time when I click on a button. I think its because the button objects i created in the constructor are not accessible in the function actionPerformed. How do I access the buttons in the function?

package game1;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.event.ActionEvent;

public class Shuffle implements ActionListener
{
    JFrame f;
    JButton b[][];

    public Shuffle()
    {
        int i,j;
        f=new JFrame("Shuffle");
        f.setLayout(new GridLayout(3,3));
        f.setVisible(true);

        JButton b[][]=new JButton[3][3];

        /*  
        for(int i=0;i<button.length;i++)
        {
            button[i] = new JButton();
            button[i].setText(Integer.toString(i+1));
        } 
        */
        int t=1;
        for (i=0;i<3;i++)
        {
            for(j=0;j<3;j++)
            {
                if(i==2 && j==2)
                {
                    b[i][j]=new JButton();
                    f.add(b[i][j]);
                    t=t+1;                  
                }
                else
                {
                    b[i][j]=new JButton(""+t+"");
                    f.add(b[i][j]);
                    t=t+1;
                }
            }
        }
        for (i=0;i<3;i++)
        {
            for(j=0;j<3;j++)
            {
                b[i][j].addActionListener(this);                    
            }
        }
    }

    public void actionPerformed(ActionEvent e)
    {
        int x,y;
        for(int i=0;i<3;i++)
        {
            for(int j=0;j<3;j++)
            {
                if(e.getSource()==b[i][j])
                {
                    x=i;y=j;
                    System.out.println(x+" "+y);
                }                   
            }
        }   
    }

    public static void main(String[] args) 
    {
        new Shuffle();
    }
}

Solution

  • You've declared a local variable b in the constructor, which hides the field b. Don't do this. Instead of

    JButton b[][] = new JButton[3][3];
    

    just write

    b = new JButton[3][3];
    

    which will assign the array to the field, instead of to a local variable.