package util;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.net.URL;

import javax.swing.JPanel;

/**
 *  Displays a JPEG or GIF Image in a JPanel Component.
 *
 * @author     T
 * @created    4. August 2001
 */
public class ImagePanel extends JPanel {

  private Image img;
  private Dimension dimension;
  private URL imageFile;


  public ImagePanel( URL u, Dimension d ) {
    dimension = d;
    imageFile = u;
    init();
  }


  private void init() {
    setBackground( Color.white );
    img = getToolkit().getImage( imageFile );
    try {
      MediaTracker tracker = new MediaTracker( this );

      tracker.addImage( img, 0 );
      tracker.waitForID( 0 );
    }
    catch ( Exception e ) {
    }
  }


  private void drawImage( int w, int h, Graphics2D g2 ) {
    BufferedImage bi = (BufferedImage) createImage( w, h );
    Graphics2D big = bi.createGraphics();

// .. use rendering hints from DemoSurface ..
    big.setRenderingHints( g2.getRenderingHints() );
    big.setBackground( getBackground() );
    big.clearRect( 0, 0, w, h );

    int iw = img.getWidth( this );
    int ih = img.getHeight( this );

    int w_off = ( w - iw ) / 2;
    int h_off = ( h - ih ) / 2;

    big.drawImage( img, w_off, h_off, iw, ih, this );
    g2.drawImage( bi, 0, 0, this );
  }


  public void paint( Graphics g ) {
    Graphics2D g2 = (Graphics2D) g;

    g2.setBackground( getBackground() );
    g2.clearRect( 0, 0, dimension.width, dimension.height );
    g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON );
    g2.setRenderingHint( RenderingHints.KEY_RENDERING,
        RenderingHints.VALUE_RENDER_QUALITY );
    drawImage( dimension.width, dimension.height, g2 );
  }
}

