//======================================================================//  PROJECT:            _programming.java_//  FILE:               Buttoner.java//  PURPOSE:            Chapter 12 lablet//  VERSION:            2.0//  TARGET:             Java v1.1//  UPDATE HISTORY:     2.0     12/4/98    1.1 event model//                      1.0     7/28/97    the version in _p.j_//======================================================================//------------------------------- NOTES --------------------------------/*    To use this applet, place the files "Buttoner.class," "GraphicButton.class,"    and "AnimatedButton.class" in the same directory or folder as the HTML    document, along with a collection of gifs, representing the down and    the animated up images of the button. Then, embed the following HTML    (with appropriate values) in the main document:	    <APPLET CODE = "Buttoner.class" WIDTH = 82 HEIGHT = 27>        <PARAM name = "pattern" value = "ab*.gif">        <PARAM name = "numPix"  value = "3">        <PARAM name = "label"   value = "Home">        <PARAM name = "destURL" value = "some URL">    </APPLET>	    PARAMETERS:         pattern (REQUIRED): The name template of the button pictures.  In the            example above, the pictures would be named "ab0.gif,"  "ab1.gif,"            and "ab2.gif".  The picture numbered 0 will be used for the down            picture. For best results, these gifs should be the size specified            in the WIDTH and HEIGHT arguments.            If this argument isn't present or is malformed, the applet will            default to using an ordinary button instead of a GraphicButton.        numPix (OPTIONAL): The number of pictures.  This must be at least 2            and will default to 2 if missing, incorrectly written, or too small.        label (OPTIONAL): The name that will appear in the button.  The label            will be centered in the button, so if it is too long, you may have            to adjust the WIDTH and HEIGHT arguments (the class will shrink            the images to fit the label, but can't grow them beyond the            applet size).        destURL (OPTIONAL): If specified and valid, this is the destination            the browser will go to when the button is clicked.*///------------------------------ IMPORTS -------------------------------	import java.applet.*;import java.awt.*;import java.awt.event.*;import java.net.*;          // for URL and MalformedURLException	import myWidgets.*;         // for GraphicButton, AnimatedButton //========================== Buttoner CLASS ============================/** * This applet is designed to place a custom animated button in a Web document. */public class Buttoner extends Applet implements ActionListener{    private AnimatedButton theButton;	private Button         backupButton;	private Image[]        images;	private int            numImgs;	private String         theLabel;	private URL            destURL;		/**     * Get the images, construct the GraphicButton, lay it out     * as the only component in the applet, and register it as a     * source of ActionEvents.     */    public void init()    {        // Get all the parameters, sometimes using our own utilities (see below).        String pattern = getParameter("pattern");        numImgs        = getIntParameter("numPix", 2);        if (numImgs < 2)        {             numImgs = 2;        }        theLabel       = getParameter("label");        destURL	       = getURLParameter("destURL", null);        // Construct the button and add it to the applet.        images = new Image[numImgs];        Dimension size = getSize();        if (loadImages(pattern))        {            theButton = new AnimatedButton(images, theLabel, 100);            theButton.setSize(size.width, size.height);            add(theButton);            theButton.addActionListener(this);        }        else	// Failed to make a GraphicButton, so default to an ordinary Button.        {            backupButton = new Button(theLabel);            backupButton.setSize(size.width, size.height - 4);            add(backupButton);            backupButton.addActionListener(this);        }    }	    /**     * Handle a mouse click in the graphic or default button by sending     * the browser to the URL given by the applet parameter.     */    public void actionPerformed(ActionEvent e)    {    	Object source = e.getSource();        if (((source == theButton) || (source == backupButton)) && (destURL != null))        {            getAppletContext().showDocument(destURL);        }    }    /**     * Get the images with the given pattern name and load them into the     * images[] array.     * RETURNS: true if and only if all images were successfully loaded.     */    private boolean loadImages(String pattern)    {        // First, parse the pattern, splitting it into the base part,        // before '*', and the extension part, after '*'.  For example,        // "bttn*.gif" would split into the base string "bttn" and        // extension string ".gif".        String  base,                extension;        int starIndex = pattern.indexOf('*');        try        {            base = pattern.substring(0, starIndex);            extension = pattern.substring(starIndex + 1);        }        catch (IndexOutOfBoundsException e)         {             showStatus("Bad pattern parameter");            return false;        }		        // Wait for the images to load, and signal by returning false        // if any are broken.        showStatus("Loading images...");        MediaTracker tracker = new MediaTracker(this);        for (int i = 0; i < numImgs; i++)        {            images[i] = getImage(getCodeBase(), base + i + extension);            tracker.addImage(images[i], i);            try            {                tracker.waitForID(i);            }            catch (InterruptedException e)            { }            if (tracker.isErrorID(i))            {                showStatus("Failed to load image " + i);                return false;            }        }        showStatus("Images loaded");        return true;	// Indicate that loading was successful.    }		//------------- Methods a well-behaved applet should have ----------	    /**     * RETURNS: an arbitrarily long array of three strings, one for each     * the applet expects.     * The strings describe, respectively, the parameter name, its type,     * and its description.     */    public String[][] getParameterInfo()    {        String[][] aboutParams = {            {"pattern", "String", "base*extension"},            {"numPix",  "int",    "number of images"},            {"label",   "String", "button label"},            {"destURL", "URL",    "destination when clicked"}};        return aboutParams;    }	    /**     * RETURNS: a String giving information about the applet.  A browser     * might use this in an About box.     */    public String getAppletInfo()    {        return "Graphic Button applet. Copyright 1997, Rick Decker";    }	    //------------------ Handy parameter-getting methods ---------------	    /**     * Try to get the parameter with the given name.  If there's no such     * parameter or if the value is incorrectly formatted, return the given     * default value.     * RETURNS: an int corresponding to the parameter, or the default     * value, if the parameter doesn't represent a legal int     * CALLED BY: init()     */    private int getIntParameter(String paramName, int defaultValue)    {        try        {            return (Integer.parseInt(getParameter(paramName)));        }        catch (NumberFormatException e)        {            return defaultValue;        }    }    /**     * Like getIntParameter, except that here we're getting a URL.     * RETURNS: a URL object corresponding to the parameter, or the default     * value, if the parameter is malformed     * CALLED BY: init()     */    private URL getURLParameter(String paramName, URL defaultValue)    {	        try        {            return (new URL(getParameter(paramName)));        }        catch (MalformedURLException e)        {             return defaultValue;        }    }}