Header javaperspective.com

5.4. Layouts
Last updated: 1 February 2013.

This chapter explains how to place components in a GUI with a layout manager. A layout manager is an object that controls the size and position of components within a GUI. The Java API provides a set of standard layout managers.

You can apply a layout manager directly to a top-level container like JFrame or, for more flexibility, use JPanel objects. A JPanel object is a transparent container with no decoration that is used as a content pane to which you can add components and apply a layout manager. In fact, a GUI is usually an aggregation of JPanel objects wherein each JPanel object has its own layout manager. A JPanel object can contain other JPanel objects.

When placing a component in a container, a layout manager has complete control over the component's size. You can give hints to a layout manager about the size you want for a component by calling upon it one or more of the following methods provided by the class JComponent: setMaximumSize, setMinimumSize and setPreferredSize. Nonetheless, the layout manager has the final say on a component's size. Depending on the situation, the layout manager can take into account the preferred, minimum or maximum size of a component. In particular, the maximum size is generally taken into account when the top-level container is enlarged.

A key point to remember is that if you add or remove components after a GUI has been displayed onscreen, you must call the method validate provided by the class Container on the top-most container of the GUI in order to validate its layout. Otherwise, the changes will not take effect.

Note that you can build a GUI with no layout manager at all. In that case, you would be using absolute positioning. However, the major downside with absolute positioning is that the top-level container may behave unpredictably when it is resized.

A layout manager is a class that implements the interface LayoutManager. Some containers have a default layout manager. For example, FlowLayout is the default layout manager for the class JPanel.

You can apply a layout manager to a container in two ways:

The next tutorials will show you how to use the following standard layout managers:

You are here :  JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.4. Layouts
Next tutorial :  JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.4. Layouts  >   5.4.1. How to use FlowLayout

Copyright © 2013. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7