import javax.swing.*;
import java.beans.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
public class Preview extends JComponent implements PropertyChangeListener, Runnable
{
ImageIcon thumbnail = null;
File file = null;
Thread td;
public void run()
{
thumbnail = null;
while (!td.interrupted)
{
if (isShowing())
{
loadImage();
repaint();
td = null;
}
}
}
public Preview(JFileChooser fc)
{
setPreferredSize(new Dimension(100, 200));
setBorder(BorderFactory.createEtchedBorder());
fc.addPropertyChangeListener(this);
}
public void loadImage() {
if (file == null) {
thumbnail = null;
return;
}
ImageIcon tmpIcon = new ImageIcon(file.getPath());
if (tmpIcon != null) {
if (tmpIcon.getIconWidth() > 90) {
thumbnail = new ImageIcon(tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT));
} else { //Non c'è bisogno della miniatura
thumbnail = tmpIcon;
}
}
}
public void propertyChange(PropertyChangeEvent e)
{
boolean update = false;
String prop = e.getPropertyName();
//Se la directory è cambiata, non mostra l'immagine.
if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(pr op)) {
file = null;
update = true;
//Se un file viene selezionato, individua quale.
} else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equal s(prop)) {
file = (File) e.getNewValue();
update = true;
if (td != null)
{
td.interrupt();
}
}
//Aggiorna la preview.
if (update && file != null)
{
td = new Thread(this);
td.start();
}
}
public void paintComponent(Graphics g) {
if (thumbnail == null) {
loadImage();
}
if (thumbnail != null) {
int x = getWidth()/2 - thumbnail.getIconWidth()/2;
int y = getHeight()/2 - thumbnail.getIconHeight()/2;
if (y < 0) {
y = 0;
}
if (x < 5) {
x = 5;
}
thumbnail.paintIcon(this, g, x, y);
}
}
}