BoxLayout in Java Swing

Updated:

By

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"));
		getContentPane().add(panel);
		pack();
		setVisible(true);
	}

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

}

Output:

BoxLayout in Java Swing

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments