Java Swing How to - Center vertical column of components with BoxLayout








Question

We would like to know how to center vertical column of components with BoxLayout.

Answer

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
/*w ww  . j ava 2s.c o m*/
public class Main extends JFrame {
  public Main() {
    Box box = new Box(BoxLayout.Y_AXIS);
    add(box);

    JLabel label = new JLabel("I'm centered");
    label.setAlignmentX(JComponent.CENTER_ALIGNMENT);

    box.add(Box.createVerticalGlue());
    box.add(label);
    box.add(Box.createVerticalGlue());
  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.setSize(300, 300);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}