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.
Do not set the preferred size of your buttons. This will cause serious visual issues for users who have desktop fonts which are different from yours.
You should let the button define its own preferred size. The best way to augment the preferred height is with GridBagConstraints.ipady:
c.ipady = 24;
Another option is to use JButton.setMargin to give each button an additional margin:
Insets margin = new Insets(12, 0, 12, 0);
back.setMargin(margin);
welcome.setMargin(margin);
Forcing the left and right sides to have equal widths is more difficult. GridBagLayout is not capable of doing that. The weightx
field only determines the distribution of extra space, when the window is wider than it needs to be in order to accommodate all child components’ preferred sizes. If the columns have different widths to begin with, distributing the extra space with weightx
will not make their widths equal.
Personally, I don’t think forcing the two sides to have equal widths will add any value. If you insist on the left and right sides being exactly equal width, you will have to abandon the use of GridBagLayout. SpringLayout can do it, but it’s difficult to use. If you’re willing to introduce a third-party dependency, something like MiG Layout may be able to do it.