Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 

Swing Chapter 4. (The basics) Layout Managers. Easy for reading, Click here!

Custom Search
Swing Chapter 4. (The basics) Layout Managers. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 1/7 



Next Page (2/7) Next Page
Subpages: 1. Layouts overview 
2. Comparing common layout managers
3.
Using GridBagLayout
4. Choosing the right layout
5. Custom layout manager: part I -Label/field pairs
6. Custom layout manager: part II - Common interfaces
7. Dynamic layout in a JavaBeans container

Chapter 4. Layout Managers

In this chapter:

  •          Layouts overview
  •          Comparing common layout managers
  •          Using GridBagLayout, by James Tan
  •          Choosing the right layout
  •          Custom layout manager: part I - Label/field pairs
  •          Custom layout manager: part II - Common interfaces
  •          Dynamic layout in a JavaBeans container

4.1    Layouts overview

In this chapter we present several examples showing how to use various layouts to satisfy specific goals, and how to create two custom layout managers that simplify the construction of many common interfaces. We also show how to construct a basic container for JavaBeans which must be able to manage a dynamic number of components. But before we present these examples it is helpful to understand the big picture of layouts, which classes use their own custom layouts, and exactly what it means to be a layout manager.

All layout managers implement one of two interfaces defined in the java.awt package: LayoutManager or its subclass, LayoutManager2. LayoutManager declares a set of methods that are intended to provide a straight-forward, organized means of managing component positions and sizes in a container. Each implementation of LayoutManager defines these methods in different ways accoring to its specific needs. LayoutManager2 enhances this by adding methods intended to aid in managing component postitions and sizes using constraints-based objects. Constraints-based objects usually store position and sizing information about one component and implementations of LayoutManager2 normally store one contraints-based object per component. For instance, GridBagLayout uses a Hashtable to map each Component it manages to its own GridBagConstraints object.

Figure 4.1 shows all the classes implementing LayoutManager and LayoutManager2. Note that there are several UI classes implementing these interfaces to provide custom layout functionality for themselves. The other classes--the classes we are most familar and concerned with--are built solely to provide help in laying out containers they are assigned to.

Each container should be assigned one layout manager, and no layout manager should be used to manage more than one container.

Note: In the case of several UI components shown in figure 4.1, the container and the layout manager are the same object. Normally, however, the container and the layout manager are separate objects that communicate heavily with each other.

Figure 4.1 LayoutManager and LayoutManager2 implementations

<<file figure4-1.gif>>

4.1.1    LayoutManager

abstract interface java.awt.LayoutManager

This interface must be implemented by any layout manager. Two methods are especially noteworthy:

layoutContainer(Container parent) calculates and sets the bounds for all components in the given container.

preferredLayoutSize(Container parent) calculates the preferred size requirements to lay out components in the given container and returns a Dimension instance representing this size.

4.1.2    LayoutManager2

abstract interface java.awt.LayoutManager2

This interface extends LayoutManager to provide a framework for those layout managers that use constraints-based layouts. Method addLayoutComponent(Component comp, Object constraints) adds a new component associated with a constraints-based object which carries information about how to lay out this component.

A typical implementation is BorderLayout which requires a direction (north, east, etc.) to position a component. In this case the constraint objects used are static Strings such as BorderLayout.NORTH, BorderLayout.EAST, etc. We are normally blind to the fact that BorderLayout is constraints-based because we are never required to manipulate the constraint objects at all. This is not the case with layouts such as GridBagLayout, where we must work directly with the contraint objects (instances of GridBagConstraints).

4.1.3    BoxLayout

class javax.swing.BoxLayout

BoxLayout organizes the components it manages along either the x-axis or y-axis of the owner panel. The only constructor, BoxLayout(Container target, int axis), takes a reference to the Container component it will manage and a direction (BoxLayout.X_AXIS or BoxLayout.Y_AXIS). Components are laid out according to their preferred sizes and not wrapped, even if the container does not provide enough space.

4.1.4    Box

class javax.swing.Box

To make using the BoxLayout manager easier, Swing also provides a class named Box which is a container with an automatically assigned BoxLayout manager. To create an instance of this container we simply pass the desired alignment to its constructor. The Box class also supports the insertion of invisible blocks (instances of Box.Filler--see below) allowing regions of unused space to be specified. These blocks are basically lightweight components with bounds (position and size) but no view.

4.1.5    Filler

static class javax.swing.Box.Filler

This static inner class defines invisible components that affect a container's layout. The Box class provides convenient static methods for the creation of three different variations: glue, struts, and rigid areas.

createHorizontalGlue(), createVerticalGlue(): returns a component which fills the space between its neighboring components, pushing them aside to occupy all available space (this functionality is more analagous to a spring than it is to glue).

createHorizontalStrut(int width), createVerticalStrut(int height): returns a fixed-width (height) component which provides a fixed gap between its neighbors.

createRigidArea(Dimension d): returns an invisible component of fixed width and height.

Note: All relevant Box methods are static and, as such, they can be applied to any container managed by a BoxLayout, not just instances of Box. Box should be thought of as utilities class as much as it is a container.

4.1.6    FlowLayout

class java.awt.FlowLayout

This is a simple layout which places components from left to right in a row using the preferred component sizes (i.e. size returned by getPreferredSize()) until no space in the container is available. When no space is available a new row is started. Because this placement depends on the current size of the container we cannot always guarantee in advance which row a component will be placed in.

FlowLayout is too simple to rely on in serious applications where we want to be sure, for instance, that a set of buttons will reside at the bottom of a dialog and not on it's right side. However, it can be useful as a pad for a single component to ensure that this component will be placed in the center of a container. Note that FlowLayout is the default layout for all JPanels (the only exception is the content pane of a JRootPane which is always initialized with a BorderLayout).

4.1.7    GridLayout

class java.awt.GridLayout

This layout places components in a rectangular grid. There are three constructors:

GridLayout(): creates a layout with one column per component. Only one row is used.

GridLayout(int rows, int cols): creates a layout with the given number of rows and columns.

GridLayout(int rows, int cols, int hgap, int vgap): creates a layout with the given number of rows and columns, and the given size of horizontal and vertical gaps between each row and column.

GridLayout places components from left to right and from top to bottom assigning the same size to each. It forces occupation of all available container space and shares this space evenly between components. When not used carefully this can lead to undesirable component sizing, such as text boxes three times higher than expected.

4.1.8    GridBagLayout

class java.awt.GridBagLayout, class java.awt.GridBagConstraints

This layout extends the capabilities of GridLayout to become constraints-based. It breaks the container's space into equal rectangular pieces (like bricks in a wall) and places each component in one or more of these pieces. You need to create and fill a GridBagConstraints object for each component to inform GridBagLayout how to place and size that component.

GridBagLayout can be effectively used for placement of components, if no special behavior is required on resizing. However, due to it's complexity it usually requires some helper methods or classes to handle all necessary constraints information. James Tan, a usability expert and GridBagLayout extraordinaire, gives a comprehensive overview of this manager in section 4.3. He also presents a helper class to ease the burden of dealing with GridBagConstraints.

4.1.9    BorderLayout

class java.awt.BorderLayout

This layout divides a container into five regions: center, north, south, east, and west. To specify the region to place a component in we use Strings of the form "Center," "North," etc., or the static String fields defined in BorderLayout: BorderLayout.CENTER, BorderLayout.NORTH, etc. During the layout process, components in the north and south regions will first be alotted their preferred height (if possible) and the width of the container. Once south and north components have been assigned sizes, components in the east and west regions will attempt to occupy their preferred width and any remaining height between the north and south components. A component in the center region will occupy all remaining available space. BorderLayout is very useful, especially in conjunction with other layouts as we will see in this and future chapters.

4.1.10  CardLayout

class java.awt.CardLayout

CardLayout treats all components similar to cards of equal size overlapping one another. Only one card component is visible at any given time (figure 4.2 illustrates). Methods first(), last(), next(), previous(), and show() can be called to switch between components in the parent Container.

Figure 4.2 CardLayout

<<file figure4-2.gif>>

In a stack of several cards, only the top-most card is visible. The following code a simple CardLayout demo, which endlessly flips through four cards containing buttons.

4.1.11  JPanel

class javax.swing.JPanel

This class represents a generic lightweight container. It works in close cooperation with layout managers. The default constructor creates a JPanel with FlowLayout, but different layouts can be specified in the constructor or assigned using the setLayout() method (see chapter 3 for more about JPanel).

Note: The content pane of a JRootPane container is a JPanel which, by default, is assigned a BorderLayout, not a FlowLayout.

Note: We have purposely omitted the discussion of several layout managers here (e.g. ViewportLayout, ScrollPaneLayout, JRootPane.RootPaneLayout, etc.) because they are rarely used by developers and are more appropriately discussed in terms of the components that rely on them. For instance, we discuss ViewportLayout and ScrollPaneLayout in chapter 7.



[ Return to Swing (Book) ]


Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color


[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3


[ More in News Section ]


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy