Java Swing How to - Layout button with BoxLayout








Question

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

Answer

import java.awt.BorderLayout;
import java.awt.Component;
//from w  ww  .  j a va  2s .  c o m
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class Main {
   public static void main(String[] argv){
   JFrame f = new JFrame();
      f.setLayout(new BorderLayout());

      JPanel panel = new JPanel();
      JButton button = new JButton("A-ha!");
      button.setAlignmentX(Component.CENTER_ALIGNMENT);
      panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
      panel.add(Box.createVerticalGlue());
      panel.add(button);
      panel.add(Box.createVerticalGlue());

      f.getContentPane().add(panel);

      f.setVisible(true);    
   }
}