Tri Nguyen Tri Nguyen - 11 months ago 91
Java Question

Java - Resize buttons in GridBagLayout

how can I make the buttons height a bit bigger and the width of right and left columns on the same size. I have tried

but it didn't work. Thanks in advance. Here's my code:

Container contentPane = getContentPane();
contentPane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(20,20,20,20);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0;

JButton back = new JButton("Back to previous menu");
c.gridx = 1;
c.gridy = 0;

JLabel welcome = new JLabel("Hi secretary, please select an action");
c.gridx = 0;
c.gridy = 0;

There's more code of buttons definition but it's just positioning themselves on the layout.


Answer Source

GridBagLayout automatically determines the height of a cell based on the components contained within its row.

If you need to make your button a specific size, then use JButton's setPreferredSize() method. Other cells in the row will adjust accordingly, but you might as well set button sizes explicitly throughout your UI.

// You'll need to import java.awt.Dimension

JButton back = new JButton("Back to previous menu");
back.setPreferredSize(new Dimension(150, 30));