/*
 * Copyright (c) 1995, 1996 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Permission to use, copy, modify, and distribute this software
 * and its documentation for NON-COMMERCIAL purposes and without
 * fee is hereby granted provided that this copyright notice
 * appears in all copies. Please refer to the file "copyright.html"
 * for further important copyright and licensing information.
 *
 * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */
package acme.beans;

import java.awt.*;
import java.io.Serializable;


public class Acme05Bean extends Canvas implements Serializable {


    public Acme05Bean() {
        this("AcmeBean Serial# 05");
    }

    public Acme05Bean(String label) {
        super();
        this.label = label;
        setFont(new Font("Dialog", Font.PLAIN, 12));
    }

    public synchronized void paint(Graphics g) {

        int width = getSize().width;
        int height = getSize().height;

        g.setColor(beanColor);
        g.fillRect(1, 1, width - 2, height - 2);
        g.draw3DRect(0, 0, width - 1, height - 1, true);

        g.setColor(getForeground());
        g.setFont(getFont());

        g.drawRect(2, 2, width - 4, height - 4);

        FontMetrics fm = g.getFontMetrics();
        g.drawString(label, (width - fm.stringWidth(label)) / 2, 
                          (height + fm.getMaxAscent() - fm.getMaxDescent()) / 2);
    }

    public Color getColor() {
        return beanColor;
    }

    public void setColor(Color newColor) {
        beanColor = newColor;
        repaint();
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String newLabel) {
        String oldLabel = label;
        label = newLabel;
        sizeToFit();
    }

    public Dimension getPreferredSize() {
        FontMetrics fm = getFontMetrics(getFont());
        return new Dimension(fm.stringWidth(label) + TEXT_XPAD, 
                             fm.getMaxAscent() + fm.getMaxDescent() + TEXT_YPAD);
    }

    public Dimension getMinimumSize() {
        return getPreferredSize();
    }

    private void sizeToFit() {
        Dimension d = getPreferredSize();
        setSize(d.width, d.height);
        Component p = getParent();
        if (p != null) {
            p.invalidate();
            p.doLayout();
        }
    }

    private Color beanColor = Color.cyan;
    private String label;
    static final int TEXT_XPAD = 12;
    static final int TEXT_YPAD = 8;
}
