![]() ![]() ![]() ![]() | Table of Contents |
This lesson tells you how to use layout managers. First, it tells you how to use the layout managers that we provide. Next, it shows how to position Components without using a layout manager. Finally, it tells you how to create your own layout manager.The layout managers we provide range from the very simple (FlowLayout and GridLayout) to the special purpose (BorderLayout and CardLayout) to the ultra-flexible (GridBagLayout).
BorderLayout
BorderLayout is the default layout manager for all Windows, such as Frames and Dialogs. It uses five areas to hold components: north, south, east, west, and center. All extra space is placed in the center area. Here's a picture of a program that puts one button in each area.
![]()
CardLayout
Use the CardLayout class when you have an area that can contain different Components at different times. CardLayouts are commonly tied to Choices, with the state of the Choice determining which Panel (group of Components) the CardLayout displays. Here are two pictures of a program that uses a Choice and CardLayout in this way.
![]()
![]()
FlowLayout
FlowLayout is the default layout manager for all Panels. It simply lays out components from left to right, centering them within their row and, if necessary, starting new rows. Both Panels in the CardLayout figure above use FlowLayouts.GridBagLayout
GridBagLayout is the most sophisticated, flexible layout manager we provide. It aligns components vertically and horizontally, without requiring that the components be the same size. Here's a picture of a program that uses a GridBagLayout to manage ten buttons in a panel.
![]()
GridLayout
GridLayouts simply make a bunch of Components have equal size, displaying them in the requested number of rows and columns. Here's a picture of a program with a Panel that uses a GridLayout to control the display of 5 buttons.
![]()
Doing Without a Layout Manager
You can position Components using absolute coordinates without using a layout manager. Here's a picture of a program with a panel that sets its layout manager to null and then positions three buttons.
![]()
Creating a Custom Layout Manager
Instead of using one of our layout managers, you can write your own. Layout managers must implement the LayoutManager interface, which specifies the five methods every layout manager must define. Here's a picture of a program that uses a custom layout manager to position components diagonally across a panel.
![]()
![]() ![]() ![]() ![]() | Table of Contents |