Getting the Number of Rows and Columns of Cells in a GridBagLayout
The number of rows and columns in a GridBagLayout automatically
grows as needed when components are added. The current number of
rows and columns can be determined by calling
getLayoutDimensions(). However, it won't return the correct
values until the components have been laid out at least once before
the call to getLayoutDimensions(). Unless you can be sure the
components have been laid out at least once, you should explicitly
call layoutContainer() to force a layout of the components.
GridBagLayout gbl = new GridBagLayout();
container.setLayout(gbl);
// Add components to container and gbl
// Force the layout of components before calling getLayoutDimensions()
gbl.layoutContainer(container);
// Get the dimensions
int[][] dim = gbl.getLayoutDimensions();
int cols = dim[0].length;
int rows = dim[1].length;
Post a comment