import java.applet.Applet; import java.awt.Frame; import java.awt.Image; import java.awt.MediaTracker; import java.io.InputStream; import java.io.IOException; import java.net.URL; import java.net.URLConnection; /** * Various utilities methods required for the applet.
* NOTE: the setup utility should be the first method called by the applet so that any subsequent classes can * use these utility methods without having to instantiate the object for themselves. */ public final class Utils extends Object { /** * used to track the loading of images */ private static MediaTracker tracker; /** * the parent applet - used to load images */ private static Applet parentApplet; static { tracker = new MediaTracker(new Frame()); } /** * don't let anyone instantiate this class */ private Utils() { } /** * the setup method should be called once at the beginning of the applet, so images can be loaded */ public static final void setup(Applet parent) { parentApplet = parent; } /** * clean up our statics */ public static final void cleanup() { tracker = null; parentApplet = null; } /** * get an image specified by its name. This image must be in the applet's codebase * (or a directory below the codebase) */ public static final Image getImage(String imageName) throws InterruptedException { if (parentApplet == null) return null; Image i = parentApplet.getImage(parentApplet.getCodeBase(),imageName); tracker.addImage(i,0); tracker.waitForAll(); return i; } /** * create an input stream from the specified fileName - used for retrieving a data file from the server */ public static InputStream getFileFromServer(String fileName) throws IOException { URL url = null; URLConnection urlConn; InputStream in = null; try { url = new URL(fileName); if( url == null) { throw new IOException("Failed to create URL object for data."); } //open a url connection to the url urlConn = url.openConnection(); in = urlConn.getInputStream(); } catch(Exception e) { throw new IOException("unable to load data file: " + e.getMessage()); } finally { url = null; urlConn = null; } return in; } }