GridLayout and number of rows and columns

邮差的信 提交于 2020-01-14 12:42:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!