当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Make Component in GridBagLayout take up same width

问题描述:

How to make Component in GridBagLayout take up same width? I have tried GridBagConstraint.weightx, but it doesn't work.

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

You need to set a preferred size for the buttons. this will give you desired outcome

网友答案:

Use a GridLayout for that section of the view. It will make the buttons all the same size, and assign as much height as needed for the tallest component, and as much width as needed for the widest.

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

The weightx constraint has more to do with how to assign extra width or height when the GUI is resized, but the cell will start with the minimum height/width it needs for that row/column.

分享给朋友:
您可能感兴趣的文章:
随机阅读: