BoxLayout Helper class - Java Swing

Java examples for Swing:BoxLayout

Introduction

We can use Box class from javax.swing package to make a BoxLayout.

A Box is a container that uses a BoxLayout as its layout manager.

The Box class has static methods to create a container with a horizontal or vertical Box layout.

createHorizontalBox() creates a horizontal box.

createVerticalBox() creates a vertical box.

import javax.swing.Box;

public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a horizontal box
    Box hBox = Box.createHorizontalBox();

    // Create a vertical box
    Box vBox = Box.createVerticalBox();
  }
}

To add a component to a Box, use its add() method, like so:

import javax.swing.Box;
import javax.swing.JButton;

public class Main {
  public static void main(String[] argv) throws Exception {
    // Create a horizontal box
    Box hBox = Box.createHorizontalBox();

    // Create a vertical box
    Box vBox = Box.createVerticalBox();

    // Add two buttons to the horizontal box
    hBox.add(new JButton("Button 1"));
    hBox.add(new JButton("Button 2"));
  }
}

Related Tutorials