【问题标题】:Resize buttons using Grid Bag Layout使用网格包布局调整按钮大小
【发布时间】:2013-10-24 15:15:42
【问题描述】:

我想将按钮的大小调整为相同大小,然后放置在 JApplet 的面板中。我试过使用

public void init() {
    // TODO start asynchronous download of heavy resources

    JButton btnWestern=new JButton("Western");
    JButton btnPop=new JButton("Pop");

    GridBagConstraints c4=new GridBagConstraints();

    JPanel jPanel1 = new JPanel();
    getContentPane().setLayout(new java.awt.GridBagLayout());
    jPanel1.setLayout(new java.awt.GridBagLayout());

    c4.gridx = 0;
    c4.gridy = 0;
    c4.insets = new Insets(36, 10, 0, 249);
    jPanel1.add(btnWestern, c4);

    c4.gridx = 0;
    c4.gridy = 1;
    c4.insets = new Insets(33, 10, 0, 249);
    jPanel1.add(btnPop, c4);

    add(jPanel1, new java.awt.GridBagConstraints());

    }

当我跑步时,这就是我得到的

但我注意到,如果我将按钮文本更改为相同或长度相同,例如

JButton btnWestern=new JButton("Button1");
JButton btnPop=new JButton("Button2");

我得到了想要的输出

我该怎么做才能确保按钮的文本长度不同,按钮大小相同?

【问题讨论】:

    标签: java jbutton layout-manager japplet gridbaglayout


    【解决方案1】:

    如果您还没有阅读过How to Use GridBagLayout 教程,我建议您阅读。 GridBagLayout 功能强大,但它也是可用的更复杂的 LayoutManager 之一。

    我相信你需要设置GridBagConstraints.fill 属性来获得你想要的行为。

    在您的情况下,这应该类似于

    c4.fill = GridBagConstraints.HORIZONTAL;

    编辑(对观察到的行为的一点解释)当您在两个按钮上使用相同的文本时,它们的计算大小最终会相同,因此它们会按照您的需要呈现。当您使用不同大小的文本时,按钮将默认以适合文本的大小呈现。 GridBagConstraints.fill 的默认值是 GridBagConstraints.NONE,它指示 LayoutManger 不调整组件的大小。将填充更改为GridBagConstraints.HORIZONTAL 告诉 LayoutManger 水平调整组件的大小以填充显示区域。

    【讨论】:

      猜你喜欢
      • 2012-03-02
      • 1970-01-01
      • 2023-03-12
      • 2016-05-05
      • 1970-01-01
      • 2015-08-16
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      相关资源
      最近更新 更多