I'm generating a chessboard using 3 JPanels
with folowing GridLayout
s:
- 8x8 for gameboard
- 1x8 for vertical markers left from the board
- 8x1 for horizontal markers under the board
I'm using resizable JFrame to contain it alltogether. I actually used this code, a little modified.
This means, after populating al three panels, add them to main JFrames panel like this:
Container contentPanel = getContentPane();
/**Create some panels**/
JPAnel 8x8 = new JPanel();
8x8.setLayout(new GridLayout(8, 8));
JPAnel 1x8 = new JPanel();
8x8.setLayout(new GridLayout(1, 8));
JPAnel 8x1 = new JPanel();
8x8.setLayout(new GridLayout(8, 1));
/**Populate frames**/
...
/**Assign frames**/
contentPanel.add(8x8, BorderLayout.CENTER);
contentPanel.add(8x1, BorderLayout.SOUTH);
contentPanel.add(1x8, BorderLayout.WEST);
It's not that bad, but it still looks like this:
The bottom line expands unther to vertical line. The larger the window is, the more obvious this issue gets.
I'd like to glue the marker lines to the chessboard so that every number will allways be aligned with appropriate line.
I tried to assign 2x2 layout to the parent frame contentPanel
however, grid layout seems to require all elements to be the same size, so it just makes bigger areas for 8x1
and 1x8
.
My approach:
contentPanel.setLayout(new GridLayout(2, 2));
contentPanel.add(1x8); //vertical markers first
contentPanel.add(8x8); //Then the chessboard
//Create empty placeholder for bottom-right corner
JPanel empty = new JPanel();
contentPanel.add(empty);
//finally add bottom markers
contentPanel.add(2x1);
But the result is even worse:
So how do I use those drunk grid layouts? Or should I start differently?
Edit:
Using gridBaglayout
:
contentPanel.setLayout(new GridBagLayout());
/**Follows as after contentPanel.setLayout(new GridLayout(2, 2)); in the prewious code**/
Result:
After playing with it a little:
/*VERTICAL MARKERS*/
//set vertical fill
c.fill = GridBagConstraints.VERTICAL;
//Set current possition to [0,0] in the grid
c.gridx = 0;
c.gridy = 0;
//Add them to panel
contentPanel.add(indexysvis, c);
/*CHESSBOARD*/
//set vertical fill to both horizontal and vertical
c.fill = GridBagConstraints.BOTH;
//Set current possition to [1,0] in the grid
c.gridx = 1;
c.gridy = 0;
contentPanel.add(sachovnice, c);
/*HORIZONTAL MARKERS*/
//set vertical fill to both horizontal
c.fill = GridBagConstraints.HORIZONTAL;
//Set current possition to [1,0] in the grid
c.gridx = 1;
c.gridy = 1;
contentPanel.add(indexyvodo,c);
It won't try to fit the window: