I created JPanel
and set the layout to GridLayout
, I set it to have 3 rows and 5 columns.
But when i added 11 JButtons to this panel it show 3 rows and 4 columns each row.
I want the JButtons to be displayed in 3 row with 5 columns.
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(3, 5));
for (int i = 0; i < 11; i++) {
JButton jButton = new JButton("Click");
panel.add(jButton);
}
frame.add(panel);
frame.setLocationByPlatform(false);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Seen for 11 objects added.
new GridLayout(3, 5)
But now look at the result of replacing the first parameter with 0.
new GridLayout(0, 5)
The trick to this is described in the Parameters section of the constructor.
Parameters
rows
- the rows, with the value zero meaning any number of rows.
cols
- the columns, with the value zero meaning any number of columns.
The same thing happens with the 4 parameter version of the GridLayout
constructor.