GridBagLayout: how to fill all empty spaces

My JFrame contains some JPanels using gridBagLayout (3 rows, one column). What is 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 what is the result (ugly result): https://docs.google.com/file/d/0Bxi2arJ2Dv9xbEo0Smd5QUN4UGc/edit?usp=sharing

I would remove these empty spaces from above and extend the second component (this is a scrollable JTable). How do I change the code?

+4
source share
2 answers

you can set the layout of the container in BorderLayout (or something similar) and create an additional JPanel using GridBagLayout and add it to the container

due to Borderlayout, JPanel will take up as much space as possible

+1
source

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

If you use c.weighty = 1 for the constraints used by the component containing the JTable, that extra vertical space will be allocated to that component. You can also make c.weightx = 1 so that the table fills all the horizontal spaces.

+27
source

Source: https://habr.com/ru/post/1492507/


All Articles