package com.mindprod.image;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import javax.swing.JComponent;
/**
* Component for viewing an Image. Simplified version of Symantec ImageViewer
* displays an Image. Does not resize the image, though may crop it.
* Thus always maintains original magnification and aspect ratio.
* Similar to IconImage.
* @author Roedy Green
*/
public class ImageViewerSwing extends JComponent
{
/**
* default Constructor
*/
public ImageViewerSwing()
{
image = null;
}
/**
* Constructor with Image.
*
* @param image the Image to be displayed .
* See the Java glossary under Image for ways to create an Image from a file.
*/
public ImageViewerSwing( Image image )
{
this();
setImage( image );
}
/**
* Set or change the current Image to display.
* setImage does a MediaTracker to ensure the Image is loaded.
* You don't have to.
* If you don't plan to use the old image again you should
* do a getImage().flush();
*
* @param image the new Image to be displayed.
* If the image jpg may have recently changed, don't use
* getImage to create it, use
* URL.openConnection()
* URLConnection.setUseCaches( false )
* Connection.getContent
* Component.createImage
*
*/
public void setImage( Image image )
{
this.image = image;
if ( image != null )
{
MediaTracker tracker;
try
{
tracker = new MediaTracker( this );
tracker.addImage( image, 0 );
tracker.waitForID( 0 );
}
catch ( InterruptedException e )
{
}
}
repaint();
}
/**
* Get the Image currently being displayed.
*
* @return the Image currently displayed or null if no Image
*/
public Image getImage()
{
return image;
}
/**
* Paints this component using the given graphics context.
* In Swing we override PaintComponent, not paint.
*
* @param g Graphics context where to paint, e.g. to screen, printer, RAM.
*/
public void paintComponent( Graphics g )
{
super.paintComponent( g );
Dimension dim = getSize();
if ( image != null )
{
int imageWidth = image.getWidth( this );
int imageHeight = image.getHeight( this );
g.drawImage ( image,
( dim.width - imageWidth ) / 2,
( dim.height - imageHeight ) / 2,
imageWidth,
imageHeight,
this );
}
else
{
g.setColor( getBackground() );
g.clearRect( 0, 0, dim.width, dim.height );
}
}
/**
* Preferred Layout size.
*
* @return the recommended dimensions to display the Image.
*/
public Dimension getPreferredSize()
{
if ( image != null )
{
return( new Dimension( image.getWidth(this), image.getHeight(this) ) );
}
else
{
return new Dimension( 10, 10 );
}
}
/**
* Minimum layout size.
*
* @return he minimum dimensions to properly display the Image
*/
public Dimension getMinimumSize()
{
return getPreferredSize();
}
/**
* Image that this viewer is currently displaying.
*/
private Image image;
}