Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding buttons using gridlayout

I'm trying to create a simple tic tac toe board made by 9x9 JButtons. I used a 2d array and a gridlayout but the result is nothing, a frame without any button. What I'm doing wrong?

import java.awt.GridLayout;
import javax.swing.*;


public class Main extends JFrame
{
    private JPanel panel;
    private JButton[][]buttons;
    private final int SIZE = 9;
    private GridLayout experimentLayout;
    public Main()
    {
        super("Tic Tac Toe");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500,500);
        setResizable(false);
        setLocationRelativeTo(null);

        experimentLayout =  new GridLayout(SIZE,SIZE);

        panel = new JPanel();
        panel.setLayout(experimentLayout);


        buttons = new JButton[SIZE][SIZE];
        addButtons();


        add(panel);
        setVisible(true);
    }
    public void addButtons()
    {
        for(int k=0;k<SIZE;k++)
            for(int j=0;j<SIZE;j++)
            {
                buttons[k][j] = new JButton(k+1+", "+(j+1));
                experimentLayout.addLayoutComponent("testName", buttons[k][j]);
            }

    }


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

    }

}

The addButton method is adding the buttons to the array and straight after to the panel.

like image 368
Imri Persiado Avatar asked Dec 16 '22 16:12

Imri Persiado


1 Answers

You need to add the buttons to your JPanel:

public void addButtons(JPanel panel) {
   for (int k = 0; k < SIZE; k++) {
      for (int j = 0; j < SIZE; j++) {
         buttons[k][j] = new JButton(k + 1 + ", " + (j + 1));
         panel.add(buttons[k][j]);
      }
   }
}
like image 144
Reimeus Avatar answered Dec 24 '22 10:12

Reimeus