// ============================================================================
// File:               ImageCanvas.java
//
// Project:            General.
//
// Purpose:            Area to show an image.
//
// Author:             Rammi
//-----------------------------------------------------------------------------
// Copyright Notice:   (c) 2002  Rammi (rammi@caff.de)
//                     This code is in the public domain.
//                     Use at own risk.
//                     No guarantees given.
//
// Latest change:      $Date$
//
// History:	       $Log$
//=============================================================================

package de.caff.gimmicks.swing;

import javax.swing.*;
import java.awt.*;

/**
 *  An area showing an image.
 *  @author <a href="mailto:rammi@caff.de">Rammi</a>
 *  @version $Revision$
 */
public class IconCanvasSwing extends JComponent {
  protected ImageIcon    icon;

  /**
   *  @param  img   the image to show
   */
  public IconCanvasSwing(Image img) {
    setImage(img);
  }

  /**
   *  Paint method. Just pint the image.
   *  @param  g   the graphics context
   */
  protected void paintComponent(Graphics g)
  {
    if (icon != null) {
      Dimension size = getSize();
      int width  = icon.getIconWidth();
      int height = icon.getIconHeight();

      icon.paintIcon(this, g, (size.width - width)/2, (size.height - height)/2);
    }
  }


  /**
   *  Get the preferred size.
   *  @return preferred size
   */
  public Dimension getPreferredSize() {
    if (icon != null) {
      int width  = icon.getIconWidth();
      int height = icon.getIconHeight();
      
      return new Dimension(width, height);
    }
    else {
      return new Dimension(1, 1);
    }
  }

  /**
   *  Get the minimum size
   *  @return the minimum size
   */
  public Dimension getMinimalSize() {
    return getPreferredSize();
  }

  /**
   *  Set the image.
   *  @param  img  new image
   */
  public void setImage(Image img) {
    if (img != null) {
      try {
	// --- be sure image is loaded ---
	MediaTracker mt = new MediaTracker(this);
	mt.addImage(img, 0);
	mt.waitForID(0);
      } catch (InterruptedException x) {
	// do nothing
      }
    }

    icon = new ImageIcon(img);

    // --- set correct size ---
    invalidate();
    repaint();
  }

}
