-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImagePreviewer.java
More file actions
41 lines (35 loc) · 1.25 KB
/
ImagePreviewer.java
File metadata and controls
41 lines (35 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package fileChooser;
import javax.swing.*;
import java.awt.*;
import java.io.File;
/**
* A file chooser accessory that previews images.
*/
public class ImagePreviewer extends JLabel {
/**
* Constructs an ImagePreviewer.
*
* @param chooser the file chooser whose property changes
* trigger an image change in this previewer
*/
public ImagePreviewer(JFileChooser chooser) {
setPreferredSize(new Dimension(100, 100));
setBorder(BorderFactory.createEtchedBorder());
chooser.addPropertyChangeListener(evt -> {
if (evt.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY) {
File file = (File) evt.getNewValue();
if (file == null) {
setIcon(null);
return;
}
// read the image into an icon
ImageIcon icon = new ImageIcon(file.getPath());
// if the icon is too large to fit, scale it
if (icon.getIconWidth() > getWidth())
icon = new ImageIcon(icon.getImage().getScaledInstance(
getWidth(), -1, Image.SCALE_DEFAULT));
setIcon(icon);
}
});
}
}