Search code examples
javaswingjbuttonjlabelgrid-layout

Java - Unusual GridLayout behaviour


Just playing around with Swing and wondering why the following code constructs a layout that seems to have three columns when the GridLayout is defined as 10 rows and 10 columns?

Can anybody explain this unusual behaviour and what in the code provided is causing this to happen?

public class MyGrid {

    public static void main (String[] args) {
        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("Y"));
                }
            }
        }
        frame.setSize(500,500);
        frame.setVisible(true);
    }

}

Solution

  • See the class javadoc of GridLayout:

    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. So, for example, if three rows and two columns have been specified and nine components are added to the layout, they will be displayed as three rows of three columns. Specifying the number of columns affects the layout only when the number of rows is set to zero.

    If you use this code

    public class MyGrid {
    
      public static void main (String[] args) {
        JFrame frame = new JFrame();
        Container container = frame.getContentPane();
        container.setLayout(new GridLayout(10,10));
        for ( int i =0; i < 100; i++ ){
          container.add( new JLabel( ""+i ) );
        }
        frame.setSize(500,500);
        frame.setVisible(true);
      }
    
    }
    

    you would see 10 rows and 10 columns. If you use i < 50 for example in the for loop, the number of columns change.