• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JFileChooserに画像プレビューを追加
#navi(../)
*JFileChooserに画像プレビューを追加 [#f95b66b6]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2006-11-20~
更新日:&lastmod;

#contents

**概要 [#d20349f5]
JFileChooserに画像のプレビュー機能を追加します。

プレビューを表示するコンポーネントは、チュートリアルの[[ImagePreview.java>http://java.sun.com/docs/books/tutorial/uiswing/components/examples/ImagePreview.java]]をそのまま利用しています。

#screenshot

**サンプルコード [#a77e7ba1]
#code{{
 fileChooser = new JFileChooser();
 fileChooser.setAccessory(new ImagePreview(fileChooser));

 //http://java.sun.com/docs/books/tutorial/uiswing/components/examples/ImagePreview.java
 class ImagePreview extends JComponent implements PropertyChangeListener {
   private static final int PREVIEW_WIDTH  = 90;
   private static final int PREVIEW_MARGIN = 5;
   private ImageIcon thumbnail = null;
   private File file = null;
   public ImagePreview(JFileChooser fc) {
     setPreferredSize(new Dimension(PREVIEW_WIDTH+PREVIEW_MARGIN*2, 50));
     fc.addPropertyChangeListener(this);
   }
   public void loadImage() {
     if(file == null) {
       thumbnail = null;
       return;
     }
     ImageIcon tmpIcon = new ImageIcon(file.getPath());
     if(tmpIcon == null) return;
     if(tmpIcon.getIconWidth()>PREVIEW_WIDTH) {
       Image img = tmpIcon.getImage().getScaledInstance(PREVIEW_WIDTH,-1,Image.SCALE_DEFAULT);
       thumbnail = new ImageIcon(img);
     }else{
       thumbnail = tmpIcon;
     }
   }
   public void propertyChange(PropertyChangeEvent e) {
     boolean update = false;
     String prop = e.getPropertyName();
     if(JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
       file = null;
       update = true;
     }else if(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
       file = (File)e.getNewValue();
       update = true;
     }
     if(update) {
       thumbnail = null;
       if(isShowing()) {
         loadImage();
         repaint();
       }
     }
   }
   protected 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 < PREVIEW_MARGIN) x = PREVIEW_MARGIN;
       thumbnail.paintIcon(this, g, x, y);
     }
   }
 }

-&jnlp;
}}
//-&jnlp;
-&jar;
-&zip;

**解説 [#xdafc59c]
上記のファイルチューザーでは、画像ファイルを選択すると、そのプレビューが表示されます。プレビューコンポーネントは、JFileChooser#setAccessory(JComponent)メソッドで、ファイルチューザーに追加しています。

プレビュー側でファイルの選択、解除などのイベントを受け取るために、PropertyChangeListener を実装する必要があります。

**参考リンク [#r0428eb6]
-[[FileChooserDemo2 (Using Swing Components)>http://java.sun.com/docs/books/tutorial/uiswing/components/examples/index.html#FileChooserDemo2]]

**コメント [#fccf3ce2]
#comment