2

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

enter image description here

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);
}
AlpacaMan
  • 465
  • 2
  • 7
  • 24

2 Answers2

2

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1
 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

XtremeBaumer
  • 6,275
  • 3
  • 19
  • 65
  • 1
    `test.setPreferredSize(new Dimension(250,25));` Magic numbers, no more than a guess at the required size. See also [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) – Andrew Thompson Nov 11 '16 at 12:23
  • it was just a quick test you can surely replace the numbers with variables if you really want to. if he wants to stay at gridbaglayout thats the solution otherwise eh can use formlayout – XtremeBaumer Nov 11 '16 at 12:27