Christian Abbott
Christian Abbott

Reputation: 53

Placing GridLayout JPanels onto a GridBagLayout JFrame

I'm trying to place two JPanels onto a JFrame using GridBagLayout. The first JPanel uses gridLayout to create 35 columns and 27 rows of JButtons, and should have a width of 3/4 of the JFrame. This panel needs to fill the vertical space available to it. The second JPanel also uses gridLayout and should fill the last 1/4 of the main JFrame.

Unfortunately, my first JPanel (sPan) isn't even fitting properly on the screen, and is forcing the whole second JPanel (cPan) off of the screen. How can I constrain these values to take up only their allowed proportion on the screen without them moving each other around?

If I use a blank JPanel with a background colour with my code, everything works out perfectly fine:

Blank JPanel proportions [1]

However, when I use my JPanel consisting of JButtons, the proportions get completely messed up:

JButtons JPanel proportions [2]

I speculate that when I instantiate my sPan object, it's sizing each button to accommodate the size of the whole JFrame. Then when I instantiate the cPan object and try to place it next to the sPan object, the buttons aren't resizing themselves to accommodate the additional panel in the main JFrame. Does anybody know how I can fix this?

I have to use GridBagLayout for this assignment, so using normal gridLayout isn't an option. Any tips regarding what's happening would be appreciated.

Upvotes: 0

Views: 420

Answers (1)

ccjmne
ccjmne

Reputation: 9618

Could you simply deal with two columns? The first one taking 5/6 of the available width and the second one taking the 1/6th remaining?

You could try the following:

final JPanel sPan = new JPanel();
sPan.setBackground(Color.RED);
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 5 / 6f;  // change this value...
constraints.weighty = 1.00;
add(sPan, constraints);

final JPanel cPan = new JPanel();
cPan.setBackground(Color.BLUE);
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1 / 6f;  // ... and this one.
constraints.weighty = 1.00;
add(cPan, constraints);

Please note: I replaced your JPanels by some empty JPanels with a background color, so even like this you can see what's going on.

Upvotes: 1

Related Questions