1 19 20 package com.sshtools.ui.swing; 21 22 import java.awt.Dimension ; 23 import java.awt.Graphics ; 24 import java.awt.Image ; 25 import java.beans.PropertyChangeEvent ; 26 import java.beans.PropertyChangeListener ; 27 import java.io.File ; 28 import javax.swing.BorderFactory ; 29 import javax.swing.ImageIcon ; 30 import javax.swing.JComponent ; 31 import javax.swing.JFileChooser ; 32 33 public class ImagePreviewAccessory extends JComponent implements PropertyChangeListener { 34 37 ImageIcon thumbnail = null; 38 File file = null; 39 40 public ImagePreviewAccessory(JFileChooser fc) { 41 setBorder(BorderFactory.createTitledBorder("Image preview")); 42 setPreferredSize(new Dimension (100, 50)); 43 fc.addPropertyChangeListener(this); 44 } 45 46 public void loadImage() { 47 if (file == null) { 48 return; 49 } 50 ImageIcon tmpIcon = new ImageIcon (file.getPath()); 51 if (tmpIcon.getIconWidth() > 90) { 52 thumbnail = new ImageIcon (tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT)); 53 } else { 54 thumbnail = tmpIcon; 55 } 56 } 57 58 public void propertyChange(PropertyChangeEvent e) { 59 String prop = e.getPropertyName(); 60 if (prop.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) { 61 file = (File ) e.getNewValue(); 62 loadImage(); 63 repaint(); 64 } 65 } 66 67 public void paintComponent(Graphics g) { 68 if (thumbnail == null) { 69 loadImage(); 70 } 71 if (thumbnail != null) { 72 int x = getWidth() / 2 - thumbnail.getIconWidth() / 2; 73 int y = getHeight() / 2 - thumbnail.getIconHeight() / 2; 74 if (y < 0) { 75 y = 0; 76 } 77 if (x < 5) { 78 x = 5; 79 } 80 thumbnail.paintIcon(this, g, x, y); 81 } 82 } 83 } | Popular Tags |