Java Reference
In-Depth Information
Using a BoxLayout Manager
The BoxLayout class defines a layout manager that arranges components in either a single row or a
single column. You specify whether you want a row-wise or a columnar arrangement when creating the
BoxLayout object. The BoxLayout constructor requires two arguments. The first is a reference to the
container to which the layout manager applies, and the second is a constant value that can be either
BoxLayout.X _ AXIS for a row arrangement, or BoxLayout.Y _ AXIS for a column arrangement.
Components are added from left to right in a row, or from top to bottom in a column. Components in
the row or column do not spill onto the next row or column when the row is full. When this occurs, the
layout manager will reduce the size of components or even clip them if necessary and keep them all in a
single row or column. With a row of components, the box layout manager will try to make all the
components the same height, and try to set a column of components to the same width.
The container class, Box , is particularly convenient when you need to use a box layout since it has a
BoxLayout manager built in. It also has some added facilities providing more flexibility in the
arrangement of components than other containers, such as JPanel objects, provide. The Box
constructor accepts a single argument that specifies the orientation as either BoxLayout.X _ AXIS or
BoxLayout.Y _ AXIS . The class also has two static methods, createHorizontalBox() and
createVerticalBox() , that each return a reference to a Box container with the orientation implied.
As we said earlier a container can contain another container, so you can easily place a Box container inside
another Box container to get any arrangement of rows and columns that you want. Let's try that out.
Try It Out - Boxes Containing Boxes
We will create an application that has a window containing a column of radio buttons on the left, a
column of checkboxes on the right, and a row of buttons across the bottom. Here's the code:
import javax.swing.*;
import java.awt.Toolkit;
import java.awt.Dimension;
import java.awt.Container;
import java.awt.BorderLayout;
import javax.swing.border.Border;
public class TryBoxLayout {
// The window object
static JFrame aWindow = new JFrame("This is a Box Layout");
public static void main(String[] args) {
Toolkit theKit = aWindow.getToolkit(); // Get the window toolkit
Dimension wndSize = theKit.getScreenSize(); // Get screen size
// Set the position to screen center & size to half screen size
aWindow.setBounds(wndSize.width/4, wndSize.height/4, // Position
wndSize.width/2, wndSize.height/2); // Size
aWindow.setDefaultCloseOperation(JFrame.EXIT _ ON _ CLOSE);
Search WWH ::




Custom Search