Question

I want to center buttons as shown below:

expected result

Here is my code:

import java.awt.Dimension;
import javax.swing.*;
import net.miginfocom.swing.MigLayout;

public class MigLayoutTest extends JFrame {

    public static void main(String[] args) {

        JPanel content = new JPanel();
        content.setLayout(new MigLayout("center, wrap, gapy 20"));

        JButton buttonA = new JButton("button A");
        buttonA.setPreferredSize(new Dimension(100,30));
        JButton buttonB = new JButton("button B");
        buttonB.setPreferredSize(new Dimension(80,80));
        JButton buttonC = new JButton("button C");
        buttonC.setPreferredSize(new Dimension(300,40));
        JButton buttonD = new JButton("button D");
        buttonD.setPreferredSize(new Dimension(200,60));

        content.add(buttonA);
        content.add(buttonB);
        content.add(buttonC);
        content.add(buttonD);

        JFrame frame = new JFrame("MigLayout Test");
        frame.setContentPane(content);
        frame.setSize(600, 400);
        frame.setVisible(true);
    }

}

Buttons are centered, but not vertically.

Any suggestions? Thanks in advance.

Was it helpful?

Solution

The whitepaper defines the exact syntax:

al/align alignx [aligny]

Going on with:

The alignment can be specified as a UnitValue or AlignKeyword.

So, for centering the whole block along both axis, using the AlignKeyword you need two parameters:

new MigLayout("al center center, wrap, gapy 20"); // centers in both directions

Next sentence:

If an AlignKeyword is used the "align" keyword can be omitted.

Which would be:

new MigLayout("center center, wrap, gapy 20"); // centers horizontally only

doesn't work though, looks like a slight glitch in parsing the parameters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top