//  Scott DeRuiter                 4/7/03
//  Cards.java
//  Simple example of a CardLayout
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class Cards extends JApplet implements MouseListener   
{
 
	private Image [] image;
	private int index, max;
	private JPanel panel1, panel2, panel3;
	private CardLayout cards;
	private Container c;

	public Cards ( )   
    	{
		index = 0;
		max = 3;
	}

	public void init ( )  
    	{
		c = this.getContentPane();
		image = new Image[max];

		for ( int i = 0; i < image.length; i++ )   
        	{
			image[i] = getImage ( getDocumentBase ( ), "pic" + i + ".jpg" );
			WaitForImage ( this, image[i] );
		}

		panel1 = new MyPanel ( image[0] );
		panel2 = new MyPanel ( image[1] );
		panel3 = new MyPanel ( image[2] );
		cards = new CardLayout ( );
		c.setLayout ( cards );
		panel1.addMouseListener(this);
		panel2.addMouseListener(this);
		panel3.addMouseListener(this);
		c.add ( panel1, "First" );
		c.add ( panel2, "Second" );
		c.add ( panel3, "Third" );

		getContentPane().setBackground( Color.blue );
	}

	public void WaitForImage ( JApplet component, Image image )   
    	{
		MediaTracker tracker = new MediaTracker ( component );
		try  
        	{
			tracker.addImage ( image, 0 );
			tracker.waitForID ( 0 );
		}
		catch ( InterruptedException e )   
        	{
			e.printStackTrace ( );   
		}
	}
	
	class MyPanel extends JPanel   
    	{
		private Image pict;

   		public MyPanel ( Image im )   
        	{
			pict = im;
		}

		public void paintComponent(Graphics g) 
        	{
			super.paintComponent ( g );
			g.drawImage ( pict, 0, 0, this );
		}
	}

	public void mousePressed(MouseEvent evt) 
    	{
		cards.next ( c );
	}
	public void mouseEntered(MouseEvent evt) { }
	public void mouseExited(MouseEvent evt) { }
	public void mouseClicked(MouseEvent evt) { }
	public void mouseReleased(MouseEvent evt) { }
}

Back to Lesson 29 Examples

Back to Java Main Page