package yi.gui.helper;

/**
 * ImagePreviewAccessory is an accessory which can be set for JFileChooser to
 * preview the image selected in the file chooser.
 *
 * Example: (See yi.iu.imgdb.desc.gui.ImageDescFrame for the context)
 *
 * JFileChooser fileChooser = new JFileChooser(".");
 * javax.swing.filechooser.FileFilter imageFilter = new ExtensionFileFilter("Image Files", new String[]{"JPG", "JPEG", "gif"});
 * fileChooser.addChoosableFileFilter(imageFilter);
 * fileChooser.addChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
 * fileChooser.setAccessory(new ImagePreviewAccessory(fileChooser));
 * fileChooser.setMultiSelectionEnabled(true);
 * int status = fileChooser.showOpenDialog(null);
 * if (status == JFileChooser.APPROVE_OPTION) {
 *     File[] selectedFile = fileChooser.getSelectedFiles();
 *     ...
 * }
 */

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

public class ImagePreviewAccessory extends JLabel implements PropertyChangeListener {
  private static final int PREFERRED_WIDTH = 128;
  private static final int PREFERRED_HEIGHT = 128;

  public ImagePreviewAccessory(JFileChooser chooser) {
    setVerticalAlignment(JLabel.CENTER);
    setHorizontalAlignment(JLabel.CENTER);
    chooser.addPropertyChangeListener(this);
    setPreferredSize(new Dimension(PREFERRED_WIDTH, PREFERRED_HEIGHT));
  }

  public void propertyChange(PropertyChangeEvent changeEvent) {
    String changeName = changeEvent.getPropertyName();
    if (changeName.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
      File file = (File)changeEvent.getNewValue();
      if (file != null) {
        ImageIcon icon = new ImageIcon(file.getPath());
        if (icon.getIconWidth() > PREFERRED_WIDTH) {
          icon = new ImageIcon(icon.getImage().getScaledInstance(PREFERRED_WIDTH,-1, Image.SCALE_DEFAULT));
          if (icon.getIconHeight() > PREFERRED_HEIGHT) {
            icon = new ImageIcon(icon.getImage().getScaledInstance(-1, PREFERRED_HEIGHT, Image.SCALE_DEFAULT));
          }
        }
        setIcon(icon);
      }
    }
  }
}

