Adding Buttons Using Gridlayout

I am trying to create a simple tic tac toe board made by 9x9 JButtons. I used a 2d array and gridlayout, but the result is nothing, a frame without a button. What am I 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 adds buttons to the array immediately after the panel.

Thanks for the advanced.

+4
source share
2 answers

You need to add 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]); } } } 
+8
source
 // add buttons to the panel INSTEAD of the layout // experimentLayout.addLayoutComponent("testName", buttons[k][j]); panel.add(buttons[k][j]); 

Further tips:

  • Do not JFrame , just keep a link to it for as long as necessary. Expand the scope only when adding or changing functionality.
  • Instead of setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); use setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); as shown in this answer .
  • Instead of setSize(500,500); use panel.setPreferredSize(new Dimension(500,500)); . Or, even better, stretch JButton to make SquareButton , which returns the preferred size equal to the largest preferred width or height. The latter ensures that the GUI is the size that should be, the square and allowing enough space for the text to display.
  • Instead of setLocationRelativeTo(null); use setLocationByPlatform(true); as shown in the answer associated with paragraph 2.
  • Add pack() to setVisible(true); , which ensures that the GUI is the size that must be in order to display the content.
  • Instead of setResizable(false) call setMinimumSize(getSize()) .
  • Launch and update the GUI on the EDT. See Concurrency in Swing for more details.
+4
source

All Articles