Java Swing How to - Vertical layout with BoxLayout








Question

We would like to know how to vertical layout with BoxLayout.

Answer

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
//  w w  w .j  a  v a  2 s  . c  o m
public class Main extends JFrame {

  private JLabel jLabelOne = new JLabel();
  private JLabel jLabelTwo = new JLabel();
  private JPanel panel = new JPanel();
  private BoxLayout boxLayout = new BoxLayout(panel, BoxLayout.Y_AXIS);

  public Main() {

    panel.setLayout(boxLayout);

    jLabelOne.setAlignmentX(CENTER_ALIGNMENT);
    jLabelTwo.setAlignmentX(CENTER_ALIGNMENT);

    jLabelOne.setText("This is text one");
    jLabelTwo.setText("This is text two");

    panel.add(jLabelOne);
    panel.add(jLabelTwo);

    panel.setAlignmentX(CENTER_ALIGNMENT);
    add(panel);
    setSize(300, 300);
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setLocationRelativeTo(null);
    setVisible(true);
  }

  public static void main(String args[]) {
    new Main();
  }
}