GridBagLayout: how to fill all empty spaces
Asked Answered
G

2

10

I've have a JFrame contains some JPanels using a gridBagLayout (3 rows, one column). That's my code:

Container main_container = getContentPane();
GridBagLayout layout = new GridBagLayout();
main_container.setLayout(layout);
GridBagConstraints c = new GridBagConstraints();

StatoMagazzini jpanel_stato_magazzini = new StatoMagazzini();
c.gridx = 1;
c.gridy = 2;
c.fill = GridBagConstraints.BOTH;
layout.setConstraints(jpanel_stato_magazzini, c);

AcquistoLotto jpanel_acquisto = new AcquistoLotto(i, jpanel_stato_magazzini);
c.gridx = 1;
c.gridy=1;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.FIRST_LINE_START;
layout.setConstraints(jpanel_acquisto, c);

ButtonPanel jpanel_button_panel = new ButtonPanel(i);
c.gridx=1;
c.gridy=3;
c.anchor = GridBagConstraints.CENTER;
layout.setConstraints(jpanel_button_panel, c);

main_container.add(jpanel_acquisto);
main_container.add(jpanel_stato_magazzini);
main_container.add(jpanel_button_panel);
pack();

and that's the result (a ugly result): https://docs.google.com/file/d/0Bxi2arJ2Dv9xbEo0Smd5QUN4UGc/edit?usp=sharing

i would eliminate that empty spaces on top and extend the second component (that is a scrollable JTable). How i should modify code?

Goldsmith answered 20/7, 2013 at 20:5 Comment(0)
G
2

you could set the layout of the container to BorderLayout (or something equivalent) and create an extra JPanel with the GridBagLayout and add it to the container

because of Borderlayout, the JPanel will take as much space as possible

Goatsucker answered 20/7, 2013 at 20:10 Comment(1)
Nice, just use borderlayout without gridbaglayout and it works.Goldsmith
B
45

When a GridBagLayout has more space than it needs, it distributes that extra space using the weightx and weighty properties of each cell. If no cells have a non-zero weight property, the extra space is not allocated to any cell, and instead all cells are centered, and sized to their preferred width/height.

If you do c.weighty = 1 for the constraints used by the component containing the JTable, that component will be allocated all extra vertical space. You may also want to do c.weightx = 1 so the table will fill all horizontal space.

Bobble answered 21/7, 2013 at 14:26 Comment(1)
Actually, this is the "technically correct" answer.Foss
G
2

you could set the layout of the container to BorderLayout (or something equivalent) and create an extra JPanel with the GridBagLayout and add it to the container

because of Borderlayout, the JPanel will take as much space as possible

Goatsucker answered 20/7, 2013 at 20:10 Comment(1)
Nice, just use borderlayout without gridbaglayout and it works.Goldsmith

© 2022 - 2024 — McMap. All rights reserved.