Will
Will

Reputation: 179

Accessing buttons within GridLayout

I am making Tic Tac Toe with many intermeshing classes and I encountered a slight problem. In my version I am trying to make the board size variable, which means the buttons that represent each square cannot be referenced easily. Is there a way to identify which button is clicked if so, how? Thanks!

public class GameView extends JFrame{  
    private static final long serialVersionUID = -2869672245901003704L;
    public TicBoard game;
    private GridLayout view;

    public GameView(int height, int width)//height and width are coordinates (-y,x) across all classes
    {
        super("Tic Tac Toe");
        game = new TicBoard(height, width);
        view = new GridLayout(height,width);

        this.setLayout(view);
        for(int h = 0; h<height; h++)
            for(int w = 0;w<width;w++)
                this.add(game.getButton(h,w));

    }       
}

Upvotes: 1

Views: 165

Answers (1)

Harry Joy
Harry Joy

Reputation: 59650

Is there a way to identify which button is clicked if so, how?

Yes.

Add ActionListener to buttons then in actionPerformed(ActionEvent e){...} method you will have e.getSource() method to identify which has triggered this method means which button is pressed.

Upvotes: 4

Related Questions