Java Swing How to - Leave space in BoxLayout with Strut








Question

We would like to know how to leave space in BoxLayout with Strut.

Answer

/*from   w w  w  .jav  a 2 s  .co m*/
import java.awt.BorderLayout;
import java.awt.Font;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class Main {

  private static JPanel createLogin() {
    JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
    JLabel label = new JLabel("login panel.");
    label.setFont(label.getFont().deriveFont(Font.ITALIC, 24f));
    label.setAlignmentX(0.5f);
    label.setBorder(new EmptyBorder(0, 20, 0, 20));
    p.add(Box.createVerticalStrut(36));
    p.add(label);
    p.add(Box.createVerticalStrut(144));
    return p;
  }

  public static void main(String[] args) {
    JFrame f = new JFrame("Test");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(createLogin(), BorderLayout.CENTER);
    JLabel admonition = new JLabel("CopyRight java2s.com.", JLabel.CENTER);
    f.add(admonition, BorderLayout.SOUTH);
    f.pack();
    f.setVisible(true);
  }
}