Making a GridBagLayout Fill the Container

By default, a gridbag layout arranges its components in the smallest area that satisfies the preferred sizes of the components. If the container is larger than this area, the cluster of components is centered within the container. This example demonstrates how to spread the excess space among all the cells in the gridbag layout.

It is possible to control exactly how much excess space is distributed among the gridbag layout cells. See Setting the Stretchyness of Rows and Columns in a GridBagLayout Using Layout Weights for more details.

GridBagLayout gbl = new GridBagLayout(); container.setLayout(gbl); // Add components to container and gbl // Force the layout of components before calling getLayoutWeights() // otherwise the result of getLayoutWeights() is not valid gbl.layoutContainer(container); // Set weights of all columns and rows to 1 double[][] weights = gbl.getLayoutWeights(); for (int i=0; i<2; i++) { for (int j=0; j<weights[i].length; j++) { weights[i][j] = 1; } } gbl.columnWeights = weights[0]; gbl.rowWeights = weights[1];

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.