1 package com.melloware.jukes.file.image;
2
3 import java.awt.Dimension;
4 import java.awt.Graphics;
5 import java.awt.Image;
6 import java.beans.PropertyChangeEvent;
7 import java.beans.PropertyChangeListener;
8 import java.io.File;
9
10 import javax.swing.ImageIcon;
11 import javax.swing.JComponent;
12 import javax.swing.JFileChooser;
13
14
15
16
17
18
19
20
21
22
23 public final class ChooserImagePreview
24 extends JComponent
25 implements PropertyChangeListener {
26
27 File file = null;
28 ImageIcon thumbnail = null;
29
30 public ChooserImagePreview(JFileChooser fc) {
31 setPreferredSize(new Dimension(100, 50));
32 fc.addPropertyChangeListener(this);
33 }
34
35 public void loadImage() {
36 if (file == null) {
37 thumbnail = null;
38 return;
39 }
40
41
42
43
44 ImageIcon tmpIcon = new ImageIcon(file.getPath());
45 if (tmpIcon != null) {
46 if (tmpIcon.getIconWidth() > 90) {
47 thumbnail = new ImageIcon(tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT));
48 } else {
49 thumbnail = tmpIcon;
50 }
51 }
52 }
53
54 public void propertyChange(PropertyChangeEvent e) {
55 boolean update = false;
56 String prop = e.getPropertyName();
57
58
59 if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
60 file = null;
61 update = true;
62
63
64 } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
65 file = (File)e.getNewValue();
66 update = true;
67 }
68
69
70 if (update) {
71 thumbnail = null;
72 if (isShowing()) {
73 loadImage();
74 repaint();
75 }
76 }
77 }
78
79 protected void paintComponent(Graphics g) {
80 if (thumbnail == null) {
81 loadImage();
82 }
83 if (thumbnail != null) {
84 int x = (getWidth() / 2) - (thumbnail.getIconWidth() / 2);
85 int y = (getHeight() / 2) - (thumbnail.getIconHeight() / 2);
86
87 if (y < 0) {
88 y = 0;
89 }
90
91 if (x < 5) {
92 x = 5;
93 }
94 thumbnail.paintIcon(this, g, x, y);
95 }
96 }
97 }