user3626083
user3626083

Reputation: 13

Grid Layout behaviour in java

Why when I run this code the window has 3 columns and 10 rows? I thought that it should have 10 columns and 10 rows.

Code:

JFrame frame = new JFrame();
Container container = frame.getContentPane();
container.setLayout(new GridLayout(10,10));
for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        if (i >= j) {
            container.add(new JButton("X"));
        } else {
            container.add(new JLabel("*"));
        }
    }
}
frame.setSize(500, 500);
frame.setVisible(true);

Upvotes: 1

Views: 278

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You have only add 25 items to the grid, and so the layout preferentially maintains the row count you entered, and adds enough columns to fill the items added. If you want 10 by 10, you'll need to add more items (empty JLabels will work) as placeholder components.

If you want 10 columns and variable number of rows, then use these settings:

container.setLayout(new GridLayout(0, 10));

Edit
Per the GridLayout API:

When both the number of rows and the number of columns have been set to non-zero values, either by a constructor or by the setRows and setColumns methods, the number of columns specified is ignored. Instead, the number of columns is determined from the specified number of rows and the total number of components in the layout.

Upvotes: 1

Related Questions