import java.awt.*;
import java.awt.image.*;

public class ImageButton extends Canvas 
{
    public static final int NORMAL = 0;
    public static final int CLICKED = 1;
    public static final int GREYED = 2;

    private Image images[] = new Image[3];

    private int buttonState = NORMAL;

    /**
     * Constructs an ImageButton
     */
    public ImageButton(Image tmpImages[])
    {
       images = tmpImages;
    }

    /**
     * Gets the current buttonState id for the button
     *
     * @return     the button state integer id
     */
	public int getButtonState() 
    {
	    return buttonState;
	}

    /**
     * Sets the current buttonState id for the button
     *
     * @param   buttonState     the button state integer id
     */
	protected void setButtonState( int tmpButtonState ) 
    {
	    if ( tmpButtonState != buttonState ) 
        {
    		buttonState = tmpButtonState;
            repaint();
    	}
	}

    /**
     * Overrides awt.Component.disable() to also set the button state.
     */
    public void disable() 
    {
        setButtonState( GREYED );
        super.disable();
    }

    /**
     * Overrides awt.Component.enable() to also set the button state.
     */
    public void enable() 
    {
        setButtonState( NORMAL );
        super.enable();
    }

    /**
     * Overrides awt.Component.paint() to paint the current border and image.
     *
     * @param     g     The Graphics in which to draw
     */
    public void paint( Graphics g )
    {
        Dimension size = size();

        int imageWidth = images[buttonState].getWidth( this );
        int imageHeight = images[buttonState].getHeight( this );
        g.drawImage( images[buttonState], 0, 0, this );
    }

    /**
     * Overrides awt.Component.preferredSize() to return the preferred size of the button.
     * This assumes the images (if more than one) are all the same size.  It also calculates
     * the maximum insets from all borders and adds them to the image dimensions.
     *
     * @param     g     The Graphics in which to draw
     */
    public Dimension preferredSize() 
    {
        Dimension pref = new Dimension();
       
        int maxWidthAdd = 0;
        int maxHeightAdd = 0;
        for ( int i = 0; i <= GREYED; i++ ) 
        {
           maxWidthAdd = Math.max( maxWidthAdd, images[i].getWidth(this));
           maxHeightAdd = Math.max( maxHeightAdd, images[i].getHeight(this));
        }
        pref.width  = maxWidthAdd;
        pref.height = maxHeightAdd;

        return pref;
    }
}
