by Dinesh Thakur Category: Swing

The BoxLayout layout manager is similar to FlowLayout in that, the components are placed in the order in which they are added and each component gets to have its own size. But unlike FlowLayout, the BoxLayout layout manager arranges components in either a single row or a single column. In other words, the components you add to BoxLayout are added vertically from top to bottom or horizontally from left to right. In BoxLayout, components will not continue on the next line or columns when there is insufficient room. The components that are out of range will not be shown. This layout manager is useful for creating toolbars or vertical button bars.

The constructor used for creating BoxLayout layout manager is

BoxLayout(java.awt.Container target, int axis}

It creates a layout manager that will layout components either left to right or top to bottom as specified in the axis parameter. The parameter target is a reference to the container to which layout manager applies and the parameter axis is a constant value that can be either BoxLayout.X_AXIS for left to right layout or Boxlayout.Y_AXIS for top to bottom layout.

                       Constructors and methods in the BoxLayout class.


Constructors and Methods


BoxLayout(Container cont, int axis)

Constructs a box layout manager that lays the specified containers in the specified axis.

Dimension maximumLayoutSize(Container cont)

Returns the maximum dimension the specified container can use to layout components.

Dimension minimumLayoutSize(Container cont)

Returns the minimum dimensions needed to layout the specified container's component.

Dimension preferredLayoutSize(Container cont)

Returns the preferred dimensions for this layout when the components of the specified container are given .

Program demonstrates the JBoxLayout class:

import javax.swing.*;

import java.awt.*;
class BoxLayoutExample extends JFrame
    JButton [] Buttons;
       int i;
       Container c = getContentPane();
       setLayout(new BoxLayout(c,BoxLayout.Y_AXIS));
       JButton Btnfirst = new JButton("C");
       JButton BtnSecond = new JButton("C++");
       JButton BtnThird= new JButton("Visual Basic");
       JButton Btnfour = new JButton("Java");
  class BoxLayoutJavaExample
      public static void main(String args[])
         BoxLayoutExample frame = new BoxLayoutExample();
         frame.setTitle("BoxLayout Java Example");

BoxLayout in Java Swing Example

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles