Java Swing How to - Position JButtons vertically one after another with Box








Question

We would like to know how to position JButtons vertically one after another with Box.

Answer

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
//from   w w w.ja v  a2  s . com
public class Main extends JPanel {

  JButton jbt1 = new JButton("Button1");
  JButton jbt2 = new JButton("Button2");
  JButton jbt3 = new JButton("Button3");
  JButton jbt4 = new JButton("Button4");

  public Main() {
    Box box = Box.createVerticalBox();
    box.add(jbt1);
    box.add(jbt2);
    box.add(jbt3);
    box.add(jbt4);

    add(box);
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.add(new Main());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationByPlatform(true);
    frame.pack();
    frame.setVisible(true);
  }
}