package com.knutejohnson.demos; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.net.*; import javax.swing.*; public class ImageObserverExample extends JPanel { private Image image; private volatile boolean appFlag; public ImageObserverExample(URL url) { try { // use createImage instead of getImage to avoid caching image = getToolkit().createImage(url); } catch (Exception e) { e.printStackTrace(); } } public ImageObserverExample(String fname) { try { image = getToolkit().createImage(fname); } catch (Exception e) { e.printStackTrace(); } } public void paintComponent(Graphics g) { g.drawImage(image,0,0,this); } public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { // if this is an application and not an applet // check the status of the width and height info // if both values are available, set the preferred size of our // component and call pack on the our top level container if (appFlag && (infoflags & ImageObserver.WIDTH) > 0 && (infoflags & ImageObserver.HEIGHT) > 0) { setPreferredSize(new Dimension(width,height)); ((Window)getTopLevelAncestor()).pack(); } return super.imageUpdate(img,infoflags,x,y,width,height); } public static void main(final String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { JFrame f = new JFrame("ImageObserverExample"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ImageObserverExample ioe = new ImageObserverExample(args[0]); ioe.appFlag = true; f.getContentPane().add(ioe,BorderLayout.CENTER); f.pack(); f.setVisible(true); } }); } }