BoxLayout Manager Example Java Swing

BoxLayout Manager Example Java Swing


BoxLayout lays out the components in a horizontal or vertical line. An axis – either BoxLayout.X-AXIS or BoxLayout.Y-AXIS is specified at the time of construction and determines the orientation of the components.

Components laid out along the x-axis are laid out horizontally, and components laid out along the y-axis are laid out vertically. Components are laid out top to bottom or left to right in the order in which they are added to their container.

BoxLayout sizes components laid out horizontally or vertically at their preferred widths or preferred heights, respectively. For a horizontal layout, if all of components are not the same height, BoxLayout attempts to set the height of component vertically according to its vertical alignment. For vertical layouts, the component’s width is adjusted in the same manner as component height for horizontal layout.

The following program on BoxLayout shows a JFrame that contains two containers, each of which contains buttons. Both containers have a BoxLayout as their layout manager; the container on the left lays out components along the X_AXIS, and the container on the right lays out components along the Y_AXIS.

BoxLayout

Box horbox = Box. createHorizontalBox();
Box verbox = Box. createVerticalBox();

The first statement creates a Box that displays its components from left to right and second statement creates a Box that displays its components from top to bottom. These two methods returns an object of Box class. Box is a subclass of java.awt.Container.

Buttons are added to the first box(horizontal box, horbox) and images are added to the second box(vertical box, verbox).

Leave a Reply

Your email address will not be published. Required fields are marked *