A Panel that resizes itself when the image size becomes known.
publicclassImagePanelextends Panel {
Image im;
Frame frame;
publicImagePanel(Image i) {
im = i;
}
publicImagePanel(Image i,Frame f) {
im = i;
frame = f;
}
publicboolean imageUpdate(Image img,int infoflags,int x,int y,int w,int h) {
if (frame!=null && (infoflags&HEIGHT)!=0 && (infoflags&WIDTH)!=0 && w>0 && h>0) {
Rectangle bounds = getBounds();
if (bounds.width<w || bounds.height<h) { // Too small; enlarge
// Note that this does not work ...
setSize(w,h);
invalidate(); // my dimensions changed
// getParent().validate();
frame.pack();
frame.show();
}
}
returnsuper.imageUpdate(img,infoflags,x,y,w,h);
}
public Dimension getPreferredSize() {
if (im == null) returnnew Dimension(150,187);
int w = im.getWidth(this);
if (w<0) w = 150;
int h = im.getHeight(this);
if (h<0) h = 187;
returnnew Dimension(w,h);
}
public Dimension getMinimumSize() {
return getPreferredSize();
}
publicvoid paint(Graphics g) {
// eerst de achtergrond tekenen
int w = im.getWidth(this);
int h = im.getHeight(this);
if (w>0 && h>0) {
Dimension siz = getSize();
g.drawImage(im,(siz.width-w)/2,(siz.height-h)/2,this);
} else g.drawImage(im,0,0,this);
// dan de (hopelijk min of meer transparante lightweight)
// componenten
super.paint(g);
}
// Avoid flicker when the image comes in
publicvoid update(Graphics g) {
paint(g);
}
}