GridLayout and the number of rows and columns

Does GridLayout never respect the number of rows and columns that you specify if you don't fill it out completely?

I am creating a GridLayout with 3 rows and 4 columns. However, I add only 9 components. In the end, he shows me these 9 components in a 3x3 grid, not a 3x4 grid (with only one component in the third row (and two spaces)).

+4
source share
2 answers

Just fill the empty cells with empty elements (e.g. JLabel ), for example:

 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 displays them as

 0 1 2 3 4 5 6 7 9 
+4
source

not a 3x4 grid (with only one component in the third row (and two spaces)).

Then you should create a GridLayout using:

 setLayout(new GridLayout(0,4)); 

It tells the layout that you don't know how many rows you have, but you want 4 columns. Thus, the columns will be filled before moving to the next row.

No need for empty components.

+28
source

Source: https://habr.com/ru/post/1347978/


All Articles