12.4 CardLayout



The CardLayout allows you to create the rough equivalent of a "tabbed dialog", which in more sophisticated environments has actual file-folder tabs running across one edge, and all you have to do is press a tab to bring forward a different dialog. Not so in the AWT: The CardLayout is simply a blank space and you're responsible for bringing forward new cards. (The JFC/Swing library contains tabbed panes that look much better and take care of all the details for you.)

This example will combine more than one layout type, which seems rather difficult at first since only one layout manager can be operating for an applet or application. This is true, but if you create more Panel objects, each one of those Panels can have its own layout manager and then be integrated into the applet or application as simply another component, using the applet or application's layout manager. This gives you much greater flexibility as seen in the following example:

Case Study: CardLayout1.java

This example begins by creating a new kind of Panel: a ButtonPanel. This contains a single button, placed at the center of a BorderLayout, which means that it will expand to fill the entire panel. The label on the button will let you know which panel you're on in the CardLayout.

In the applet, both the Panel cards where the cards will live and the layout manager cl for the CardLayout must be members of the class because you need to have access to those handles when you want to manipulate the cards.

The applet is changed to use a BorderLayout instead of its default FlowLayout, a Panel is created to hold three buttons (using a FlowLayout), and this panel is placed at the "worth" end of the applet. The cards panel is added to the "center" of the applet, effectively occupying the rest of the real estate.

When you add the ButtonPanels (or whatever other components you want) to the panel of cards, the add( ) method's first argument is not "North", "South", etc. Instead, it's a string that describes the card. Although this string doesn't show up anywhere on the card, you can use it if you want to flip that card using the string. This approach is not used in action( );
instead the first( ), next( ), and lst( ) methods are used. Check your documentation for the
other approach.

In Java, the use of some sort of "tabbed panel" mechanism is quite important because (as you'll see later) in applet programming the use of pop-up dialogs is heavily discouraged. For Java 1.0 applets, the CardLayout is the only viable way for the applet to have a number of different forms that "pop up" on command.


Next Page