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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
package test;
import java.awt.*;
import java.beans.*;
import javax.swing.*;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
public final class ImagePanel extends JPanel {
public static final String IMAGE_PROPERTY = "ImagePanel.image";
private InnerListener innerListener = new InnerListener();
public ImagePanel(Image image) {
super();
addPropertyChangeListener(IMAGE_PROPERTY, innerListener);
setImage(image);
}
public void dispose() {
removePropertyChangeListener(IMAGE_PROPERTY, innerListener);
innerListener = null;
setImage(null);
}
public void setImage(Image image) {
putClientProperty(IMAGE_PROPERTY, image);
}
public Image getImage() {
return (Image) getClientProperty(IMAGE_PROPERTY);
}
/** {@inheritDoc}
*/
@Override protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
Image image = getImage();
if (image != null) {
graphics.drawImage(image, 0, 0, null);
}
}
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
private class InnerListener implements PropertyChangeListener {
/** {@inheritDoc}
*/
public void propertyChange(PropertyChangeEvent event) {
String property = event.getPropertyName();
if (property.equals(IMAGE_PROPERTY)) {
Image image = getImage();
int width = 0;
int height = 0;
if (image != null) {
width = image.getWidth(null);
height = image.getHeight(null);
}
Dimension size = new Dimension(width, height);
setPreferredSize(size);
setMinimumSize(size);
repaint();
}
}
}
} |