Java BoxLayout
The Java BoxLayout class is used to arrange the components either vertically or horizontally. For this purpose, the BoxLayout class provides four constants. They are as follows:
Note: The BoxLayout class is found in javax.swing package.
Fields of BoxLayout Class
- public static final int X_AXIS: Alignment of the components are horizontal from left to right.
- public static final int Y_AXIS: Alignment of the components are vertical from top to bottom.
- public static final int LINE_AXIS: Alignment of the components is similar to the way words are aligned in a line, which is based on the ComponentOrientation property of the container. If the ComponentOrientation property of the container is horizontal, then the components are aligned horizontally; otherwise, the components are aligned vertically. For horizontal orientations, we have two cases: left to right, and right to left. If the value ComponentOrientation property of the container is from left to right, then the components are rendered from left to right, and for right to left, the rendering of components is also from right to left. In the case of vertical orientations, the components are always rendered from top to bottom.
- public static final int PAGE_AXIS: Alignment of the components is similar to the way text lines are put on a page, which is based on the ComponentOrientation property of the container. If the ComponentOrientation property of the container is horizontal, then components are aligned vertically; otherwise, the components are aligned horizontally. For horizontal orientations, we have two cases: left to right, and right to left. If the value ComponentOrientation property of the container is also from left to right, then the components are rendered from left to right, and for right to left, the rendering of components is from right to left. In the case of vertical orientations, the components are always rendered from top to bottom.
Constructor of BoxLayout class
- BoxLayout(Container c, int axis): creates a box layout that arranges the components with the given axis.
Example of BoxLayout class with Y-AXIS:
FileName: BoxLayoutExample1.java
Output:
Example of BoxLayout class with X-AXIS
FileName: BoxLayoutExample2.java
Output:
Example of BoxLayout Class with LINE_AXIS
The following example shows the effect of setting the value of ComponentOrientation property of the container to RIGHT_TO_LEFT. If we do not set the value of ComponentOrientation property, then the components would be laid out from left to right. Comment line 11, and see it yourself.
FileName: BoxLayoutExample3.java
Output:
Example of BoxLayout Class with PAGE_AXIS
The following example shows how to use PAGE_AXIS.
FileName: BoxLayoutExample4.java
Output:
The above output shows that the buttons are aligned horizontally. Now, we will display the buttons vertically using the PAGE_AXIS.
FileName: BoxLayoutExample5.java
Output: