Does GridLayout ever not honor the number of rows and columns you've specified if you don't fill it completely?
I'm creating a GridLayout with 3 rows and 4 columns. However, I'm only adding 9 components. It ends up showing me these 9 components in a 3x3 grid, rather than a 3x4 grid (with only 1 component on the third row (and two blanks)).
int getRows(): Similar to getColumns() method, we can use it to get the number of rows present in the grid layout.
You can use grid-template-columns to specify the number of columns. The number of columns is defined by the number of values in the list. Below, I'm using repeat() as shorthand to generate four values. Based on your existing code, auto auto auto auto would also work.
A GridLayout puts all the components in a rectangular grid and is divided into equal-sized rectangles and each component is placed inside a rectangle whereas GridBagLayout is a flexible layout manager that aligns the components vertically and horizontally without requiring that the components be of the same size.
A GridLayout object places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size.
rather than a 3x4 grid (with only 1 component on the third row (and two blanks)).
Then you should be creating your GridLayout using:
setLayout(new GridLayout(0,4));
It tell the layout that you don't know how many rows you have, but you want 4 columns. So the columns will be filled up before moving to the next row.
No need for empty components.
Just fill empty cells with empty items (like a JLabel
), eg:
class MyFrame extends JFrame
{
MyFrame()
{
setLayout(new GridLayout(3,4));
for (int i = 0; i < 9; ++i)
this.getContentPane().add(new JLabel(""+i));
for (int i = 0; i < 3; ++i)
getContentPane().add(new JLabel());
pack();
setVisible(true);
}
}
This layouts them as
0 1 2 3
4 5 6 7
9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With