The CardLayout Class in AWT
The CardLayout class stacks components on top of one another like a deck of cards. The CardLayout class has two constructors: the default constructor as well as one that takes the horizontal and vertical gap sizes.
The following applet animates through 10 Button objects labeled “Card 1” through “Card 10.” The next button in the set is presented every second. The CardTest applet uses the CardLayout for layout management and a Thread object to do the animation.
import java.awt.*;
import java.applet.*;
public class CardTest extends Applet implements Runnable
{
// a Thread to act as the timer
private Thread timer;
public void init()
{
// create a new CardLayout
setLayout(new CardLayout());
// create 10 buttons stacked within the CardLayout
for(int i = 1; i <= 10; i++)
{
// the second parameter is a mandatory String representation
// of the Button to add
add(new Button("Card " + i), "Card " + i);
}
// register this applet as a Thread
timer = new Thread(this);
}
public void start()
{
timer.start();
}
public void stop()
{
timer = null;
}
// define the run method as prescribed in the Runnable interface
public void run()
{
CardLayout layout = (CardLayout)getLayout();
// get a reference to this thread
Thread t = Thread.currentThread();
// loop while the thread is active
while(t == timer)
{
layout.next(this);
// wait one second between updates
Try
{
timer.sleep(1000);
}
catch(InterruptedException e) { return; }
}
} // run
} // CardTest
There are some notable methods included within the CardLayout class that were not used in the above code listing. The first and last methods display the first and last component in the layout, respectively. In addition to the next method, there is also a previous method, which displays the previous component in the layout. Each of these four methods takes a Container as its parameter; in this case, it is the applet itself.
A fifth CardLayout method worth looking at is the show method. It takes a Container as its first parameter and a String as its second. The String should match one of the String objects sent as a parameter to the add method when creating the layout. For instance, when adding buttons to the layout I associated the button labeled “Card 1” with the string “Card 1,” the button labeled “Card2” was associated with the string “Card 2,” and so on. Therefore, the following code would display the card labeled “Card 5”:
layout.show(this, "Card 5");


LinkBack URL
About LinkBacks
Reply With Quote

LinkBacks Enabled by vBSEO
Bookmarks