Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback, please email oracle-forums_moderators_us@oracle.com

GridBagLayout to create a board

843806Feb 3 2009 — edited Feb 3 2009
Hi all.

I am using a GridBagLayout to create a board of 11x11 squares. These squares will be buttons, and all will be of the same size. But it has to be like a board made of bricks. The first row will be formed by 11 buttons. The first square of the second row has to start in the middle of the first square of the first row. The third row will be as the first row, and the fourth row as the second row...

My intention has been to use a GridBagLayout where the grid were formed by 11x21 squares, and each square will use two cells of width. I was thinking of putting the first button on the (0,0), the second on the (2,0), (4,0) ... (20,0).The first button of the second row on the (1,1), the second button of the second row on the (1,3)... (1,21).

This is what I have used:
import gato.PanelGato;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JFrame;

public class ButtonTest {

	private static PanelGato panel;

	public static void main (String[] args) {
		panel = new PanelGato();
		panel.setLayout(new GridBagLayout());
		JFrame frame = new JFrame ();
		createPanel();
		frame.setPreferredSize(new Dimension(800,800));
		frame.add(panel);
		frame.pack();
		frame.setVisible(true);
	}

	public static void createPanel () {
		GridBagConstraints c = new GridBagConstraints();
		for (int i=0; i<11; i++) {
			int modOdd = 0;
			if (i%2==1)
				modOdd = 1;		
			for (int j=0; j<11; j++) {
//The 11 squares of a row are created here. gridy = the number of row, gridx = twice the number of row (+ 1 if it is a even row)
//The gridwidth = 2 because I want the buttons to use two cells.
				c = new GridBagConstraints();
				c.gridy = i;
				c.gridx = 2*j+modOdd;
				c.gridwidth=2;//case B: c.gridwidth=1
				panel.add(new JButton(),c);
			}
		}
	}
}
The result is a simple board, where the second row starts in the same place as the first row, and all the board is a square.
In the case B, where c.gridwidth=1, the result is like a chessboard where the buttons are only the black squares. It is not a "brick board", because the first button of the second row starts where the first one of the first row ends.

Could anyone help me?
Thank you very much for reading it :)
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 3 2009
Added on Feb 3 2009
2 comments
1,087 views