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.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BoxLayoutDemo extends JFrame  
{
  public BoxLayoutDemo() 
  {
    Container contentPane = getContentPane();
    contentPane.setLayout(new FlowLayout());

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

    horbox.add(new JButton("Button 1"));
    horbox.add(new JButton("Button 2"));
    horbox.add(new JButton("Button 3"));

    verbox.add(new JButton(new ImageIcon("bird4.gif")));
    verbox.add(new JButton(new ImageIcon("bird6.gif")));
    verbox.add(new JButton(new ImageIcon("bird5.gif")));

    contentPane.add(horbox);
    contentPane.add(verbox);

    pack();                           // take minimum size of the frame sufficient to display the components
    setVisible(true);
  }   
  public static void main(String args[])
  {
    new BoxLayoutDemo();
  }
}

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 Comment

Your email address will not be published.