2 package net.sf.openrocket.gui.preset;
7 import java.beans.PropertyChangeEvent;
8 import java.beans.PropertyChangeListener;
12 * From a JavaLobby article by Michael Urban: http://www.javalobby.org/java/forums/t49462.html
14 public class ImagePreviewPanel extends JPanel
15 implements PropertyChangeListener {
17 private int width, height;
18 private ImageIcon icon;
20 private static final int ACCSIZE = 155;
23 public ImagePreviewPanel() {
24 setPreferredSize(new Dimension(ACCSIZE, -1));
28 public void propertyChange(PropertyChangeEvent e) {
29 String propertyName = e.getPropertyName();
31 // Make sure we are responding to the right event.
32 if (propertyName.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
33 File selection = (File)e.getNewValue();
36 if (selection == null)
39 name = selection.getAbsolutePath();
42 * Make reasonably sure we have an image format that AWT can
43 * handle so we don't try to draw something silly.
46 name.toLowerCase().endsWith(".jpg") ||
47 name.toLowerCase().endsWith(".jpeg") ||
48 name.toLowerCase().endsWith(".gif") ||
49 name.toLowerCase().endsWith(".png")) {
50 icon = new ImageIcon(name);
51 image = icon.getImage();
58 private void scaleImage() {
59 width = image.getWidth(this);
60 height = image.getHeight(this);
64 * Determine how to scale the image. Since the accessory can expand
65 * vertically make sure we don't go larger than 150 when scaling
68 if (width >= height) {
69 ratio = (double)(ACCSIZE-5) / width;
71 height = (int)(height * ratio);
74 if (getHeight() > 150) {
75 ratio = (double)(ACCSIZE-5) / height;
77 width = (int)(width * ratio);
80 ratio = (double)getHeight() / height;
82 width = (int)(width * ratio);
86 image = image.getScaledInstance(width, height, Image.SCALE_DEFAULT);
89 public void paintComponent(Graphics g) {
93 * If we don't do this, we will end up with garbage from previous
94 * images if they have larger sizes than the one we are currently
95 * drawing. Also, it seems that the file list can paint outside
96 * of its rectangle, and will cause odd behavior if we don't clear
97 * or fill the rectangle for the accessory before drawing. This might
98 * be a bug in JFileChooser.
100 g.fillRect(0, 0, ACCSIZE, getHeight());
101 g.drawImage(image, getWidth() / 2 - width / 2 + 5,
102 getHeight() / 2 - height / 2, this);