MigLayout and vertically centered components

I want the 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);
    }

}

The buttons are centered, but not upright.

Any suggestions? Thanks in advance.

+4
source share
1 answer

The technical document defines the exact syntax:

al / align alignx [aligny]

Continuation:

Alignment can be specified as UnitValue or AlignKeyword.

So, to center the entire block along both axes, using AlignKeyword, you need two parameters:

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

Next suggestion:

If AlignKeyword is used, the keyword "align" may be omitted.

What will happen:

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

does not work, but looks like a small glitch when analyzing the parameters.

+5

Source: https://habr.com/ru/post/1538581/


All Articles