Reputation: 1051
I have a JPanel
with GridBagLayout
set. It has 2 columns and 1 row (2 cells). Every cell contains one JPanel
which contains one JLabel
(type of component is insignificant).
The JLabel
in the left cell has width attribute set to 100px. The JLabel
in the right cell has width attribute set to 50px. In such case the left cell extends a little and it's wider than the right cell.
I thought that GridBagLayout
expands cell only when contained components take too much space.
Is it a GBL bug?
Any idea how I can solve this problem?
Upvotes: 0
Views: 868
Reputation: 13012
I am afraid this is a difficult question to answer because GridBagLayout
doesn't arrange it's columns and rows this way. If you have two columns and two components the columns will size themselves as the sizes of the largest components put into those columns. So your left column is bigger, because your left component is bigger.
You can adjust how much of any spare space a cell takes by adjusting your component's corresponding GridBagConstraints
attributes. The weight attributes (weighty
& weightx
) control how much of any spare space the columns (weightx
) and rows (weighty
) take up. If for example your JPanel
s were using GridBagConstraints
objects called rightGbc
and leftGbc
you could use the following code to alter their relative sizes.
leftGbc.weightx = 0.5;
rightGbc.weightx = 1;
This means that the right column will take up twice as much spare space as the left column and therefore (hopefully) make up for the difference in the size of your components.
Using the weight attributes can feel like a very abstract process, and it can take a while to get used to them, but once you start using them for a while you will get it. Depending on which components you are using, there are other quirks which can effect how much affect the weight attributes have on the columns/rows.
Upvotes: 1
Reputation: 51553
Any idea how I can solve this problem?
Java Swing does not work the same way as CSS/HTML. You create the components in Swing and let the GUI worry about the sizing.
Without knowing what you're trying to accomplish, all I can do is say define the Swing components and let the GridBagLayout manage the layout.
If you want the grid areas to be the same size, you would use the GridLayout.
Upvotes: 1