Search code examples
javaswingjframelayout-managergrid-layout

Components in GridLayout don't show properly


I create a GridLayout Frame with 2 rows and 3 column. I put 3 JLabel in the first row and each column. When I try to run, the third label is in the second row and the first column as show below

screenshot

Why does it happen?

Here the code

  JFrame windows = new JFrame("Shop");
  windows.setLayout(new GridLayout(2,3));
  JLabel prodlabel = new JLabel("Products");
  windows.add(prodlabel);
  JLabel spacelabel = new JLabel(" mid ");
  windows.add(spacelabel);
  JLabel shoplabel = new JLabel("Shopping List");
  windows.add(shoplabel);
  windows.setSize(1360, 728);
  windows.setVisible(true);

Solution

  • It has to do with the way GridLayout behaves when both the rows and columns are set to non-zero values. The LayoutManager decides on a column count itself based on the number of rows and the container's component count.

    You can instead set the number of rows to 0 and set columns to 3. The LayoutManager will add more rows as you add more components to the container.

    windows.setLayout(new GridLayout(0,3));
    

    Edit: Wording, and here's a link to the Java Tutorial on GridLayout which may or may not have more information related to the matter.