import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.AffineTransform;

import javax.swing.*;

public class ShapeLabel extends JLabel
{
  private static final long serialVersionUID = 1L;
  
  private static final Dimension MINIMUM_SIZE = new Dimension(50,50);
  private static final Color GOLD   = new Color(173, 156, 101);
  private static final Color PURPLE = new Color( 69,   0, 132);
  
  private Shape shape;

  /**
   * Default Constructor.
   */
  public ShapeLabel()
  {
    super();
    shape = null;
  }
  
  /**
   * Set the Shape.
   * 
   * @param shape  The shape.
   */
  public void setShape(Shape shape)
  {
    this.shape = shape;
  }
  
  /**
   * Get the minimum size of this Component.
   * 
   * @return  The minimum size
   */
  public Dimension getMinimumSize()
  {
    return MINIMUM_SIZE;
  }
  
  /**
   * Get the preferred size of this Component.
   * 
   * @return  The preferred size
   */
  public Dimension getPreferredSize()
  {
    Rectangle bounds = shape.getBounds();
    return new Dimension((int)bounds.getWidth()+(int)bounds.getX(), 
                         (int)bounds.getHeight()+(int)bounds.getY());
  }
  
  /**
   * Render this Component.
   * 
   * @param g  The rendering engine to use
   */
  public void paint(Graphics g)
  {
    super.paint(g);
    
    if (shape != null)
    {
      // Remember state information
      Graphics2D g2 = (Graphics2D)g;
      AffineTransform at = g2.getTransform();
      Color color = g2.getColor();
      Paint paint = g2.getPaint();
      RenderingHints hints = g2.getRenderingHints();

      // Scale appropriately
      Rectangle componentBounds = getBounds();
      Rectangle shapeBounds     = shape.getBounds();
      double xScale = (double)componentBounds.getWidth() / 
          (double)(shapeBounds.getWidth() + shapeBounds.getX());
  
      double yScale = (double)componentBounds.getHeight() / 
          (double)(shapeBounds.getHeight() + shapeBounds.getY());
      
      double scale = Math.min(xScale,  yScale) - 0.10;

      
      // Render
      g2.scale(scale, scale);
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g2.setPaint(PURPLE);
      g2.fill(shape);
      g2.setColor(GOLD);
      g2.draw(shape);
    
      // Reset the state information
      g2.setPaint(paint);
      g2.setColor(color);
      g2.setRenderingHints(hints);
      g2.setTransform(at);
    }
  }
 
}
