使 GridBagLayout 中的组件占用相同的宽度

Make Component in GridBagLayout take up same width

如何让GridBagLayout中的Component占用相同的宽度?我已经试过了GridBagConstraint.weightx,但是没用。

static void test3() {
    JFrame f = new JFrame("Test");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(480, 360);
    Container pane = f.getContentPane();
    pane.setLayout(new GridBagLayout());

    String[] a = {
            "Lorem ipsum dolor sit amet",
            "consectetur adipisicing",
            "elit, ",
            "sed do",
            "eiusmod",
    };
    for (int i = 0; i < 5; i++) {
        GridBagConstraints c = new GridBagConstraints();
        c.gridx = i % 3;
        c.gridy = i / 3;
        c.weightx = 0.5;
        c.fill = GridBagConstraints.HORIZONTAL;
        f.add(new JButton(a[i]), c);
    }
    f.setVisible(true);
}
 static void test3() {
    JFrame f = new JFrame("Test");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(800, 360);
    Container pane = f.getContentPane();
    pane.setLayout(new GridBagLayout());

    String[] a = {
            "Lorem ipsum dolor sit amet",
            "consectetur adipisicing",
            "elit,",
            "sed do",
            "eiusmod",
    };
    for (int i = 0; i < 5; i++) {
        JButton test=new JButton(a[i]);
        GridBagConstraints c = new GridBagConstraints();
        c.gridx = i %3;
        c.gridy = i /3;
        c.fill = GridBagConstraints.HORIZONTAL;
        test.setPreferredSize(new Dimension(250,25));
        f.add(test, c);
    }
    f.setVisible(true);
}

您需要为按钮设置首选大小。这会给你想要的结果

对视图的该部分使用 GridLayout。它将使所有按钮的大小相同,并为最高组件分配所需的高度,为最宽的组件分配所需的宽度。

I have tried GridBagConstraint.weightx, but it doesn't work.

weightx 约束与如何在调整 GUI 大小时分配 额外 宽度或高度有关,但单元格将从最小值开始 height/width 它需要 row/column.