BoxLayout in Java Swing

BoxLayout is a layout manager in Java Swing that arranges components either vertically or horizontally in a single line. It provides two orientation modes: X_AXIS (horizontal) and Y_AXIS (vertical), which can be set using the BoxLayout constructor.

To use BoxLayout, we first need to create a container and set its layout to BoxLayout.

Following is an example of creating a JFrame and setting its layout to BoxLayout with vertical orientation:

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class BoxLayoutDemo extends JFrame {
	public BoxLayoutDemo() {
		JPanel panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
		panel.add(new JButton("Button 1"));
		panel.add(new JButton("Button 2"));
		panel.add(new JButton("Button 3"));

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



BoxLayout in Java Swing