this.rootComponent.setLayout(new GridBagLayout());
GridBagConstraints gbc=new GridBagConstraints();
//gbc.gridwidth=2;
gbc.gridx=0;
gbc.gridy=0;
gbc.gridwidth=8;
gbc.anchor=GridBagConstraints.FIRST_LINE_START;
this.rootComponent.add(new JLabel("Test label 1"),gbc);
gbc.gridx=8;
gbc.gridy=12;
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbc.anchor=GridBagConstraints.FIRST_LINE_START;
this.rootComponent.add(new JLabel("Test label"),gbc);
Want to format it like this. grey part shows the jpanel part. Initially i want to layout the first 2 jpanel correctly . which is not working. how to fix it?
You are failing to specify any
weightx
andweighty
values to theGridBagConstraints
. Moreover yourgridwidth
values are wrong, since it only needs to be2
for the bottom mostJPanel
, for the rest it needs to be1
.Explanation of what I am doing : Consider
JPanel
sBLUE
andRED
, they are to be placed along the X-AXIS, in the ratio70:30
, with respect to each other (therefore theirweightx
will be0.7
and0.3
respectively. Since the total area along the X-AXIS is1.0
).Now both of these
BLUE
andRED JPanel
s are to be placed along the Y-AXIS, with respect to the thirdGREEN JPanel
in the ratio90:10
, therefore, both of theseBLUE
andRED
will haveweighty = 0.9
, and theGREEN JPanel
will haveweighty = 0.1
, but sinceGREEN JPanel
is suppose to occupy the whole area (with respect to X-AXIS), as occupied byBLUE
andRED JPanel
s, for that matter, itsgridwidth = 2
andweightx = 1.0
.Try this code example :
Here is the OUTPUT of the same :