package edu.princeton.toy; import java.awt.*; import java.awt.image.*; import java.io.*; import java.net.*; import javax.swing.*; /** * TResourceLoader is a convenient library of functions which allow the other classes to easily * access resources from within the JAR file. In centralizing all resource loading, we also give * ourselves the ability to change the implementation easily. */ public abstract class TResourceLoader { private static Class ANCHOR_CLASS; /** * The class for the ResourceAnchor. */ static { try { ANCHOR_CLASS = Class.forName("ResourceAnchor"); } catch (ClassNotFoundException e) { e.printStackTrace(); JOptionPane.showMessageDialog( null, "The resource loader cannot load any of Visual X-TOY's resources because your " + "JVM does not comply with the Java specification.", "JVM Error", JOptionPane.ERROR_MESSAGE ); System.exit(-1); } } private static final Toolkit TOOLKIT = Toolkit.getDefaultToolkit(); private static final ClassLoader LOADER = ANCHOR_CLASS.getClassLoader(); /** * Returns the URL object for a JARed resource. * * @param path The path of the resource relative to the root of the JAR archive. * @return The URL corresponding to the JARed resource. */ public static URL getUrl(String path) { if (path == null) throw new NullPointerException(); return LOADER.getResource(path); } /** * Returns the Image object for a JARed picture. * * @param path The path of the picture relative to the root of the JAR archive. * @return The Image corresponding to the JARed picture. */ public static Image getImage(String path) { if (path == null) throw new NullPointerException(); return TOOLKIT.getImage(LOADER.getResource(path)); } /** * Returns the InputStream object for a JARed file. * * @param path The path of the file relative to the root of the JAR archive. * @return The InputStream which reads from that file. */ public static InputStream getInputStream(String path) throws IOException { if (path == null) throw new NullPointerException(); return LOADER.getResource(path).openStream(); } /** * Returns the Reader object for a JARed file. * * @param path The path of the file relative to the root of the JAR archive. * @return The Reader which reads from that file. */ public static Reader getReader(String path) throws IOException { if (path == null) throw new NullPointerException(); return new InputStreamReader(LOADER.getResource(path).openStream()); } /** * Returns the BufferedReader object for a JARed file. * * @param path The path of the file relative to the root of the JAR archive. * @return The BufferedReader which reads from that file. */ public static BufferedReader getBufferedReader(String path) throws IOException { if (path == null) throw new NullPointerException(); return new BufferedReader(new InputStreamReader(LOADER.getResource(path).openStream())); } }