Box class is a Container for creating a single row or column of components using the BoxLayout manager.
The Box container works like a JPanel with default layout manager, BoxLayout.
You can use an inner class of Box called Box.Filler to better position components within the container.
You have three ways to create a Box, offered by one constructor and two static factory methods:
public Box(int direction)
Box horizontalBox = new Box(BoxLayout.X_AXIS);
Box verticalBox = new Box(BoxLayout.Y_AXIS);
public static Box createHorizontalBox()
Box horizontalBox = Box.createHorizontalBox();
public static Box createVerticalBox()
Box verticalBox = Box.createVerticalBox();
import java.awt.BorderLayout;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class BoxSample {
public static void main(String args[]) {
JFrame verticalFrame = new JFrame("Vertical");
verticalFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box verticalBox = Box.createVerticalBox();
verticalBox.add(new JLabel("Top"));
verticalBox.add(new JTextField("Middle"));
verticalBox.add(new JButton("Bottom"));
verticalFrame.add(verticalBox, BorderLayout.CENTER);
verticalFrame.setSize(150, 150);
verticalFrame.setVisible(true);
}
}
import java.awt.BorderLayout;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class BoxSample {
public static void main(String args[]) {
JFrame horizontalFrame = new JFrame("Horizontal");
horizontalFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box horizontalBox = Box.createHorizontalBox();
horizontalBox.add(new JLabel("Left"));
horizontalBox.add(new JTextField("Middle"));
horizontalBox.add(new JButton("Right"));
horizontalFrame.add(horizontalBox, BorderLayout.CENTER);
horizontalFrame.setSize(150, 150);
horizontalFrame.setVisible(true);
}
}