Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GridLayout and number of rows and columns

Does GridLayout ever not honor the number of rows and columns you've specified if you don't fill it completely?

I'm creating a GridLayout with 3 rows and 4 columns. However, I'm only adding 9 components. It ends up showing me these 9 components in a 3x3 grid, rather than a 3x4 grid (with only 1 component on the third row (and two blanks)).

like image 437
Paul Reiners Avatar asked Apr 13 '11 20:04

Paul Reiners


People also ask

Which method is used to find out the number of rows in the GridLayout?

int getRows(): Similar to getColumns() method, we can use it to get the number of rows present in the grid layout.

How can we specify the number of rows and columns in a grid layout?

You can use grid-template-columns to specify the number of columns. The number of columns is defined by the number of values in the list. Below, I'm using repeat() as shorthand to generate four values. Based on your existing code, auto auto auto auto would also work.

What is the difference between GridLayout and GridBagLayout?

A GridLayout puts all the components in a rectangular grid and is divided into equal-sized rectangles and each component is placed inside a rectangle whereas GridBagLayout is a flexible layout manager that aligns the components vertically and horizontally without requiring that the components be of the same size.

What is GridLayout for?

A GridLayout object places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size.


2 Answers

rather than a 3x4 grid (with only 1 component on the third row (and two blanks)).

Then you should be creating your GridLayout using:

setLayout(new GridLayout(0,4)); 

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

No need for empty components.

like image 109
camickr Avatar answered Sep 17 '22 13:09

camickr


Just fill empty cells with empty items (like a JLabel), eg:

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

0 1 2 3
4 5 6 7
9    
like image 34
Jack Avatar answered Sep 16 '22 13:09

Jack