Search code examples
javaswinglayout-managergridbaglayout

Trim column space below JTable using GridBagLayout


I have two buttons below my table. But one button almost occupy all the spaces of my table. I wanted to trim the column spaces between two buttons. Adding weight.x = 1 to my left side button won't push to the right.

gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.insets = new Insets(20, 10, 0, 0);
gbc.gridx = 0;
gbc.gridy = 0;
JTable tbl = new JTable();
tbl.setPreferredScrollableViewportSize(new Dimension(500, 200));
tbl.setRowHeight(30);

JScrollPane pane = new JScrollPane(tbl);
panelCenter.add(pane, gbc);

gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.gridx = 0;
gbc.gridy = 1;
JButton btnAdd = new JButton("Add");
panelCenter.add(btnAdd, gbc);

gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1;
gbc.weighty = 1;
JButton btnRemove = new JButton("Remove");
panelCenter.add(btnRemove, gbc);

Output: SC


Solution

  • The GridBagConstraints used with JScrollPane that holds the JTable should have its gridwidth property set to 2 to allow the JTable to occupy two columns, while everything else should use a gridwidth of 1.

    gbc.anchor = GridBagConstraints.FIRST_LINE_START;
    gbc.insets = new Insets(20, 10, 0, 0);
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = 2;  // ****** add
    JTable tbl = new JTable();
    
    // .....
    
    gbc.gridwidth = 1;  // ****** add
    

    Note of caution: I usually create a new GridBagConstraint object for every item I'm adding (unless I'm adding a true grid of items), or use a utility method to create one, in order to avoid property propagation errors.