5

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.

hold3n
  • 75
  • 1
  • 3

1 Answers1

6

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.

kleopatra
  • 51,061
  • 28
  • 99
  • 211
  • 1
    @MikaelGrev killing you would be counter-productive - then you couldn't fix it – kleopatra Apr 29 '14 at 16:18
  • @MikaelGrev MigLayout rlz :D – hold3n Apr 30 '14 at 08:02
  • @kleopatra One more question. I need to set insets and center all components vertically. I tried this way: `content.setLayout(new MigLayout("debug, insets 20 40 n 40, aligny center, fillx")); content.add(new JTextArea("Lorem ipsum dolor sit amet\n consectetur ..."), "grow, wrap"); content.add(new JButton("button A"), "grow");` Unfortunately, top inset is ignored, presumably because of vertical alignment. The question is if it is possible to centre components as long as insets 'allow' it? – hold3n May 03 '14 at 13:52