【问题标题】:Java - Resize buttons in GridBagLayoutJava - 调整 GridBagLayout 中的按钮大小
【发布时间】:2017-03-22 08:52:46
【问题描述】:

我怎样才能使按钮的高度更大一些,并且左右列的宽度相同。我试过weightxweightyheightxheighty,但没用。提前致谢。这是我的代码:

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

按钮定义的代码更多,但它只是将自己定位在布局上。

【问题讨论】:

    标签: java awt layout-manager gridbaglayout


    【解决方案1】:

    不要设置按钮的首选大小。对于使用与您不同的桌面字体的用户,这将导致严重的视觉问题。

    您应该让按钮定义自己的首选大小。增加首选高度的最佳方法是使用GridBagConstraints.ipady

    c.ipady = 24;
    

    另一种选择是使用JButton.setMargin 给每个按钮一个额外的边距:

    Insets margin = new Insets(12, 0, 12, 0);
    back.setMargin(margin);
    welcome.setMargin(margin);
    

    强制左右两边的宽度相等比较困难。 GridBagLayout 无法做到这一点。 weightx 字段仅确定额外空间的分布,当窗口比它需要的宽以容纳所有子组件的首选大小时。如果列的宽度不同,使用weightx 分配额外的空间不会使它们的宽度相等。

    就我个人而言,我不认为强制两侧具有相等的宽度会增加任何价值。如果你坚持左右两边宽度完全相等,你将不得不放弃使用 GridBagLayout。 SpringLayout 可以做到,但是使用起来比较困难。如果你愿意引入第三方依赖,像 MiG Layout 这样的东西或许可以做到。

    【讨论】:

      猜你喜欢
      • 2014-02-20
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多