Tri Nguyen Tri Nguyen - 27 days ago 22
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

weightx
weighty
heightx
heighty
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;
contentPane.add(back,c);

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


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

Picture

Answer

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));
Comments