Java Swing How to - Mix Horizontal and vertical boxes in BoxLayout








Question

We would like to know how to mix Horizontal and vertical boxes in BoxLayout.

Answer

import java.awt.Dimension;
/*  w ww .j a  v a  2 s  .co  m*/
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main {
  JLabel intro = new JLabel("The chosen name:");
  JFrame frame = new JFrame();
  JLabel name = new JLabel("JLabel");

  public Main() {    
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setContentPane(createUI());
    frame.pack();
    frame.setVisible(true);
  }

  public JPanel createUI() {
    intro.setLabelFor(name);
    final JButton button = new JButton("Pick a new name...");
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
    panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 10, 20));
    intro.setAlignmentX(JComponent.CENTER_ALIGNMENT);
    name.setAlignmentX(JComponent.CENTER_ALIGNMENT);
    button.setAlignmentX(JComponent.CENTER_ALIGNMENT);
    panel.add(intro);
    panel.add(Box.createVerticalStrut(5));
    panel.add(name);
    panel.add(Box.createRigidArea(new Dimension(150, 10)));
    panel.add(button);
    return panel;
  }

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