import java.awt.*; import java.awt.image.*; import java.applet.*; import java.net.*; public class Picture extends Component { // implements ImageObserver String file; Image img; static Applet applet; Dimension minSize; public static void setApplet(Applet a) { applet = a; } public Picture(int width, int height, String file) { setSize(width,height); setMinimumSize(new Dimension(width,height)); setImage(file); repaint(); } public void setMinimumSize(Dimension d) { minSize = d; } public Dimension getMinimumSize() { // used by layout manager if (minSize != null) return minSize; else return super.getMinimumSize(); } public Dimension getPreferredSize() { // used by layout manager return getMinimumSize(); } public void setImage(String file) { if (file != null) { this.file = file; img = loadImage(file); } else { img = null; } repaint(); } Image loadImage(String fileName) { Image result = null; repaint(); try { if (applet != null) { result = applet.getImage(new URL(fileName)); } else { result = Toolkit.getDefaultToolkit().getImage(fileName); } } catch (Exception e) { System.out.println("loadImage: " + e); } return result; } public void paint(Graphics g) { Rectangle b = getBounds(); // method of Component, returns Rectangle if (img != null) { int w = img.getWidth(null); int h = img.getHeight(null); g.drawImage(img,0,0,b.height*w/h,b.height,this); } else { g.drawRect(0,0,b.width-1,b.height-1); } } public boolean imageUpdate(Image image, int flags, int x, int y, int w, int h) { // checks if whole image is there and we're talking about the right one. // repainting regardless would slowly show the image as it is loaded if (flags == ImageObserver.ALLBITS && image == img) { repaint(); } return true; // says we've handled the event } }