So I have 6 panels, all of them used a grid layout. And I put them together using gridbaglayout, here is the design I wanted
Turn out it became a total mess The "second" panel became much further away to the right The third panel is squeezed a lot to the left and it was a disaster. Here is my code for the gridbag layout
c.gridx = 0; c.gridy = 0;
add (first,c);
c.gridx = 2; //so that the second panel starts from the center and is divided evenly with the first panel
add(second,c);
c.gridx = 0; c.gridy = 1;
add(third,c);
c.gridx = 1;
add(fourth,c);
c.gridx = 2;
add(fifth,c);
c.gridx = 3;
add(sixth,c);
Any help is appreciated.
Here is (another) alternative nested layout. Panels 3 through 6 will get extra height, the extra width will be divided evenly amongst all 6 panels.
As you wrote
c.gridx = 0 and c.gridy = 0
, you forgot to specify how many columns you want thisJPanel
to occupy. In order to specify that, you should be usingc.gridwidth = 2
, which tells the layout that thisJPanel
needs space for two columns.To get an output like this:
Here is a small working example:
Add this:
c.gridwidth = 2;
Before adding the FIRST and SECOND panels, then set gridwidth back to 1 before adding the others. Alternatively you could separate them further as suggested above. You could use two FlowLayouts for each row, and add those two to another panel with a BorderLayout with NORTH/SOUTH.
I am not familiar enough with the
GridBagLayout
to quickly spot what you can improve to your code to fix this. But another approach might be possible, using nestedBorderLayout
s.Panels 'first', 'third' and 'fourth' can be placed inside one
JPanel
A
with aBorderLayout
in theNORTH
,WEST
andEAST
respectively. The same can be done for the panels 'second', 'fifth' and 'sixth' in a JPanelB
.Then you group those 2 panels (
A
andB
) in another panel with aBorderLayout
in theWEST
andEAST