I have a little issue with the GridBag Layout Manager. I am trying to display 9 panels like this:
To do so, I separated the Grid like this:
For the panels 1 to 7 there is no problem, they show up just as I want. But the issue starts with the panels S8
and S9
. As you can see, the S8
and S9
takes up half the frame, but I can't make it display like this. The S8
ends at the start of S4
, and the S9
begins at the end of S4
, I cannot handle the half space.
Only way I figured out is to put the S8
and S9
panel in another panel which takes all the frame width - but surely there must be a proper way to display these two panels without putting them in another panel!
Here is the code:
workzone.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.NORTHWEST;
c.fill = GridBagConstraints.BOTH;
c.weightx = 0.5;
c.weighty = 0.5;
c.insets = new Insets(0,0,0,0);
//S1
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
c.gridheight = 2;
workzone.add(S1, c);
//S2
c.gridx = 2;
c.gridy = 0;
c.gridwidth = 2;
c.gridheight = 1;
workzone.add(S2, c);
//S3
c.gridx = 2;
c.gridy = 1;
c.gridwidth = 2;
c.gridheight = 1;
workzone.add(S3, c);
//S4
c.gridx = 4;
c.gridy = 0;
c.gridwidth = 2;
c.gridheight = 2;
workzone.add(S4, c);
//S5
c.gridx = 7;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
workzone.add(S5, c);
//S6
c.gridx = 7;
c.gridy = 1;
c.gridwidth = 2;
c.gridheight = 1;
workzone.add(S6, c);
//S7
c.gridx = 8;
c.gridy = 0;
c.gridwidth = 2;
c.gridheight = 2;
workzone.add(S7, c);
//S8
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 5;
c.gridheigth = 1;
workzone.add(S8, c);
//S9
c.gridx = 6;
c.gridy = 2;
c.gridwidth = 5;
c.gridheight = 1;
workzone.add(S9, c);
Any ideas and propositions are welcome !
The accepted answer is appealing, but it causes section 4 to widen faster than the flanking panels as the frame is resized. This variation places panels 8 & 9 in a separate sub-panel of a
BoxLayout
.I never been a big fan of GridBagLayout. So for me I would break your GUI down into multiple panels and would probably use multiple GridLayout to achieve what you want. Something like:
For the last two
JPanel
, I would suggest you to simply add them to a newJPanel
withGridLayout
and set thisJPanel
with theGridLayout
on to theJPanel
having theGridBagLayout
. Please have a look at the code example, that resulted in actually the same output, as you were expecting :Here is the Output of the above code :
For the S9 component, your code is
Since the coordinate system begins at 0 rather than 1, I propose the code be
Generally, I create and add the components of a GridBagLayout in Y, X position order. I don't know if this is required, but it makes it easier for me to diagnose problems.
Here's what I came up with for your grid.
I have tried using
BorderLayout
to check how it works. But just posting here .. :) This process uses multiple panels inside each other. You can try this approach if this example is comfortable.