The following figures show two programs, each of which displays five buttons. The Java code for both programs is almost identical. So why do they look so different? Because they use different layout managers to control the layout of the buttons.
Note: This lesson now uses Swing!
As of October 5, 1998, the examples in this lesson have been converted to use Swing components and the text has been updated accordingly. All of the examples in this lesson are applets, which are included in the HTML file with OBJECT and EMBED tags. To run them you need Java Plug-in 1.1.1, which you can download for free. See About Our Examples for more information about running applets in the tutorial.
A layout manager is an object that controls the size and position of components in a container. Layout managers adhere to the
LayoutManagerinterface. By default, every
Containerobject has a
LayoutManagerobject that controls its layout. For
JPanelobjects, the default layout manager is an instance of the
FlowLayoutclass. For a
JFrame's content pane, the default layout manager is an instance of the
This lesson has examples of every kind of layout manager. each example can run either as an applet or as an application. The examples bring up windows that you can resize to see how resizing affects the layout.
Using Layout ManagersHere's where to learn how to use layout managers. This section gives both general rules and detailed instructions on using each of the layout managers that the AWT provides.
Creating a Custom Layout ManagerInstead of using one of the AWT's layout managers, you can write your own. Layout managers must implement the
LayoutManagerinterface, which specifies the five methods every layout manager must define.
Doing Without a Layout Manager (Absolute Positioning)You can position components without using a layout manager. Generally, this solution is used to specify absolute positions for components, and only for programs that are executed on only one platform or that use custom components. Absolute positioning is often unsuitable for platform-independent programs, since the size of components can be different on different platforms.
Common Layout Problems (and Their Solutions)Some of the most common layout problems are that components are displayed too small -- or not at all. This section tells you how to fix these and other common layout problems.