Vivid
Vivid

Reputation: 449

GridBagLayout with fixed number of columns

I just want a GridLayout which has the change to merge cells. So I found the GridBagLayout. It seems that this layout is very flexible. I don't need this flexibility. Is there a way to tell the GridBagLayout that it should use, for example, 20 columns and 10 rows over the whole width and height?? It should look like a GridLayout, but with merging cells.

Thx

Upvotes: 3

Views: 11114

Answers (2)

codenaugh
codenaugh

Reputation: 857

I wish that this was possible, as it would make my project much easier. However, this is the answer:

GridBagLayout offers no methods to explicitly define the number of rows or columns in the grid, nor does it have methods to define the size of each cell in the grid. Instead, GridBagLayout calculates the number of rows and columns in a grid by the number of Components placed on the screen. If a container has five Components lined up horizontally, then the grid consists of five columns and one row. If the Container has five Components lined up vertically, then the grid consists of one column and five rows.

I got it from: http://www2.sys-con.com/itsg/virtualcd/java/archives/0304/tabbone/index.html

For my project, I'm thinking of creating the top row and left column of my GridBagLayout with x and y number of 1 pixel by 1 pixel transparent panels to manually create an excel-like grid and put objects within that grid structure, using gridwidth and gridheight to merge the cells as desired. This should allow me an easy way to create my complicated layout and have everything resize correctly (knock on wood).

Upvotes: 0

Joseph Elcid
Joseph Elcid

Reputation: 877

As far as I know, you can use the same height and width for more than one JComponent. But you'll have to change them, where you want a merged cell.

Here is an example from how to use GridBagLayout

protected void makebutton(String name,
                          GridBagLayout gridbag,
                          GridBagConstraints c) {
    Button button = new Button(name);
    gridbag.setConstraints(button, c);
    add(button);
}

public void init() {
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    setFont(new Font("SansSerif", Font.PLAIN, 14));
    setLayout(gridbag);
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    makebutton("Button1", gridbag, c); 
    makebutton("Button2", gridbag, c);
    makebutton("Button3", gridbag, c);
    c.gridwidth = GridBagConstraints.REMAINDER; //end row
    makebutton("Button4", gridbag, c);

    c.weightx = 0.0;                //reset to the default
    makebutton("Button5", gridbag, c); //another row
    .........
}

So you don't need to specify the height and width all the time.

Upvotes: 1

Related Questions