Box simplifies working with BoxLayout : Box « Swing « Java Tutorial






  1. Box class is a Container for creating a single row or column of components using the BoxLayout manager.
  2. The Box container works like a JPanel with default layout manager, BoxLayout.
  3. You can use an inner class of Box called Box.Filler to better position components within the container.
  4. You have three ways to create a Box, offered by one constructor and two static factory methods:
public Box(int direction)
Box horizontalBox = new Box(BoxLayout.X_AXIS);
Box verticalBox = new Box(BoxLayout.Y_AXIS);

public static Box createHorizontalBox()
Box horizontalBox = Box.createHorizontalBox();

public static Box createVerticalBox()
Box verticalBox = Box.createVerticalBox();
Box simplifies working with BoxLayout
import java.awt.BorderLayout;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class BoxSample {
  public static void main(String args[]) {
    JFrame verticalFrame = new JFrame("Vertical");
    verticalFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Box verticalBox = Box.createVerticalBox();
    verticalBox.add(new JLabel("Top"));
    verticalBox.add(new JTextField("Middle"));
    verticalBox.add(new JButton("Bottom"));
    verticalFrame.add(verticalBox, BorderLayout.CENTER);
    verticalFrame.setSize(150, 150);
    verticalFrame.setVisible(true);

  }
}
Box simplifies working with BoxLayout
import java.awt.BorderLayout;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class BoxSample {
  public static void main(String args[]) {
    JFrame horizontalFrame = new JFrame("Horizontal");
    horizontalFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Box horizontalBox = Box.createHorizontalBox();
    horizontalBox.add(new JLabel("Left"));
    horizontalBox.add(new JTextField("Middle"));
    horizontalBox.add(new JButton("Right"));
    horizontalFrame.add(horizontalBox, BorderLayout.CENTER);
    horizontalFrame.setSize(150, 150);
    horizontalFrame.setVisible(true);
  }
}








14.88.Box
14.88.1.Box simplifies working with BoxLayoutBox simplifies working with BoxLayout
14.88.2.new Box(BoxLayout.Y_AXIS)
14.88.3.Working with Box.Filler: Glue and Strut
14.88.4.Creating Rigid Areas: StrutCreating Rigid Areas: Strut
14.88.5.Box.createVerticalGlue()Box.createVerticalGlue()