/* Sample Solution from Ken Been */ import java.net.*; import java.io.*; import java.applet.*; import java.awt.*; public class Hw5example extends Applet { private String[] lines; private final static int MAX_NUM_LINES = 50; private int numLines; private URL url; private BufferedReader in; public void init() { // create array of strings lines = new String[MAX_NUM_LINES]; // make it white writing on black background setBackground(Color.black); setForeground(Color.white); // create url object url = null; try { url = new URL("http://cs.nyu.edu/been/v22.0310-004/eg/hw5example/input.txt"); } catch (MalformedURLException e) { reportError("bad url"); return; } } public void start() { // create and open input stream in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); } catch (IOException e) { reportError("io problem opening input stream: " + e); return; } // Set this point in the input (the beginning) to be the point // that will be returned to whenever in.reset() is called. try { in.mark(300); } catch (IOException e) { reportError("problem marking stream: " + e); return; } } public void stop() { // close input stream try { in.close(); } catch (IOException e) { reportError("problem closing file:" + e); return; } } public void paint(Graphics g) { // reset input stream to the beginning try { in.reset(); } catch (IOException e) { reportError("couldn't reset stream: " + e); return; } // temporary string for reading in the input String s = null; // set font to be larger and more readable g.setFont(new Font("Dialog", Font.PLAIN, 20)); // placement of first string, y direction int y = g.getFont().getSize()+10; // space to skip between strings, y direction int yIncrement = g.getFont().getSize(); // number of lines read in so far numLines = 0; // read input file; create one string per line, store in array try { s = in.readLine(); } catch (IOException e) { reportError("io exception: " + e); return; } while (s != null && numLines < MAX_NUM_LINES) { lines[numLines] = s; numLines++; snapshot(y, g); y += yIncrement; try { s = in.readLine(); } catch (IOException e) { reportError("io exception: " + e); return; } } } private void snapshot(int y, Graphics g) { // placement of first string, x direction int x = 10; // space to skip between strings, in x direction int xIncrement = g.getFont().getSize()*3; // draw each string in the array for (int i = 0; i < numLines; i++) { g.drawString(lines[i], x, y); x += xIncrement; } } // just put error message into string array, and make it the only one; // will be viewed when paint() is called private void reportError(String err) { // make array of size one lines = new String[1]; // put error message there lines[0] = err; } }