问题
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)).
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/5654953/gridlayout-and-number-of-rows-and-columns