/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pdfdb.gui.panels;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.RenderingHints.Key;
import java.awt.Stroke;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
/** The panel which shows thumbnails.
* @author ug22cmg */
public class ThumbnailPanel extends JPanel
{
private static final Dimension DIMENSIONS = new Dimension(-1, 350);
private static final Key AA_KEY = RenderingHints.KEY_ANTIALIASING;
private static final Object AA_VALUE = RenderingHints.VALUE_ANTIALIAS_ON;
private static final Stroke STROKE = new BasicStroke(1);
private static final int TRANSPARENCY = Transparency.TRANSLUCENT;
private BufferedImage thumbnail = null;
private BufferedImage bi = null;
private Rectangle rect = null;
private int cachedHeight = Integer.MIN_VALUE;
private int cachedWidth = Integer.MIN_VALUE;
/** Initializes with a default size. */
public ThumbnailPanel()
{
super.setSize(DIMENSIONS);
super.setPreferredSize(DIMENSIONS);
super.setMaximumSize(DIMENSIONS);
super.setMinimumSize(DIMENSIONS);
super.setOpaque(false);
}
/** Sets the current thumbnail and repaints.
* @param thumbnail The thumbnail image (assumes correct size). */
public void setThumbnail(BufferedImage thumbnail)
{
this.thumbnail = thumbnail;
cachedWidth = Integer.MIN_VALUE;
repaint();
}
/** Gets whether the painting objects are cached or not.
* @return True if cached. */
private boolean isCached()
{
return cachedHeight == getHeight() && cachedWidth == getWidth();
}
private void drawOnImage(Graphics2D g2d)
{
rect = new Rectangle(1, 1, getWidth() - 2, getHeight() - 2);
cachedWidth = getWidth();
cachedHeight = getHeight();
g2d.setPaint(Color.WHITE);
g2d.fill(rect);
if (thumbnail != null) g2d.drawImage(thumbnail, 0, 0, this);
g2d.setPaint(Color.BLACK);
g2d.setStroke(STROKE);
g2d.draw(rect);
g2d.dispose();
}
/** Draws the component.
* @param g The graphics object to draw with. */
@Override
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
if (!isCached())
{
GraphicsEnvironment env = GraphicsEnvironment.
getLocalGraphicsEnvironment();
GraphicsDevice gd = env.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
bi = gc.createCompatibleImage(getWidth(), getHeight(), TRANSPARENCY);
drawOnImage((Graphics2D) bi.getGraphics());
}
g2d.setRenderingHint(AA_KEY, AA_VALUE);
g2d.drawImage(bi, 0, 0, null);
super.paintComponent(g2d);
}
}