简体   繁体   English

Java-调整GridBagLayout中的按钮大小

[英]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. 我已经试过weightx weighty heightx heighty ,但没有奏效。 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 : 增加首选高度的最佳方法是使用GridBagConstraints.ipady

c.ipady = 24;

Another option is to use JButton.setMargin to give each button an additional margin: 另一个选择是使用JButton.setMargin为每个按钮提供额外的边距:

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. GridBagLayout无法做到这一点。 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. 当窗口的宽度大于为容纳所有子组件的首选大小而需要的窗口时, weightx字段仅确定多余空间的分布。 If the columns have different widths to begin with, distributing the extra space with weightx will not make their widths equal. 如果开始时各列的宽度不同,则用weightx分配多余的空间将不会使它们的宽度相等。

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. 如果您坚持左侧和右侧的宽度完全相等,则必须放弃使用GridBagLayout。 SpringLayout can do it, but it's difficult to use. SpringLayout可以做到,但是很难使用。 If you're willing to introduce a third-party dependency, something like MiG Layout may be able to do it. 如果您愿意引入第三方依赖性,则可以使用MiG Layout之类的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM