Thursday, 14 May 2015

CardLayout in Java

  The CardLayout is different from the others because it enables you to create virtual screen real estate by defining multiple Cards, one of which is visible at any time. Each Card contains a panel that can contain any number of interface elements, including other panels. If you've ever used HyperCard on the Mac, you'll be familiar with this Rolodex type of interface. It's also similar to the tabbed dialog boxes that are the rage in Microsoft products, but Cards lack any built-in way to go from Card to Card; you have to provide an interface for that.

Note
Commercial widgets that implement tabbed dialog boxes are available; see the section "Extending the AWT," later in this chapter.

The example in Listing 17.31 generates a group of five cards. Each card has a button that takes you to the next card. You can tell which card you're on by looking at the button name.

Listing 17.31. Generating a group of five cards.
import java.awt.*;
import java.applet.Applet;


public class cardlayout extends Applet{
    Button the_buttons[];
    Panel  the_panels[];
    CardLayout cl;

    public void init()
    {   int i;
        int n_buttons; 
        String name;

        cl = new CardLayout(); 
        setLayout(cl); 
        n_buttons = 5; 
        the_panels = new Panel[n_buttons];
        the_buttons = new Button[n_buttons];
        //this loop creates the 5 panels and adds a button to each
        for(i=0;i<n_buttons;i++) {
            the_panels[i] = new Panel();
            name = "Button " + i;
            the_buttons[i] = new Button(name);
            the_panels[i].add(the_buttons[i]); 
            name = "Card " + i;
            //give the panel a name to be used to access it
            add(name, the_panels[i]);
        }
        cl.show(this,"Card 2");
    }
        public boolean action (Event e, Object o) {
        Dimension  d_should; 
        //when the button is clicked this takes you to the next card, 
        //it will cycle around so that when you're 
        //at card 4 this will take you to card 0
        if (e.target instanceof Button) {
            cl.next(this); 
        }
        return true;
    }

}


Clearly, you could make a tabbed dialog box interface by using a row of buttons across the top of all the cards (one for each card in the group) or with a canvas at the top with a set of tabs drawn on it.  

No comments:

Post a Comment