import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.util.*; import java.text.*; import java.net.URL; import java.io.BufferedReader; import java.io.InputStreamReader; /* * Applet which implement the stock reader excercise. */ public class StockReaderApplet extends Applet implements KeyListener{ // GUI elements TextField ticker_prompt = new TextField(6); TextField start_prompt = new TextField("01.01.99", 8); TextField stop_prompt = new TextField("31.12.99", 8); TextArea result_area = new TextArea("",4,30, TextArea.SCROLLBARS_VERTICAL_ONLY); /* * The init method builds the user interface. */ public void init(){ // BorderLayout is a good choice of LayoutManager for this // applet. We use the CENTER panel to hold the TextArea, and the // the NORTH panel to hold the other components. setLayout(new BorderLayout()); result_area.setEditable(false); add(result_area, BorderLayout.CENTER); // We put all components that we want at BorderLayout.NORTH // on common panel so that they get aligned properly. // This panel uses a FlowLayout (which is what we want for this line). // This panel is added to the NORTH panel of BorderLayout. Panel north = new Panel(); north.add(new Label("Enter a ticker: ")); north.add(ticker_prompt); ticker_prompt.addKeyListener(this); north.add(new Label("Start date: ")); north.add(start_prompt); start_prompt.addKeyListener(this); north.add(new Label("Stop date: ")); north.add(stop_prompt); stop_prompt.addKeyListener(this); add(north, BorderLayout.NORTH); } public void keyPressed(KeyEvent event) {} public void keyTyped(KeyEvent event) {} public void keyReleased(KeyEvent event){ // Check that the key-press came from the ticker_prompt, // and that the user pressed the enter key. DateFormat df = new SimpleDateFormat("dd.MM.yy"); Date curDate, strtDate, stpDate; try{ strtDate = df.parse(start_prompt.getText()); stpDate = df.parse(stop_prompt.getText()); }catch(Exception e){ result_area.append("\nIlligal start or stop date!\n\n"); return; } if(event.getKeyCode() == KeyEvent.VK_ENTER){ // Get ticker and read from server. try{ URL stock = new URL("http://www.stud.ifi.uio.no/~in104/Quotes/Oslo/" + ticker_prompt.getText()); BufferedReader in = new BufferedReader(new InputStreamReader(stock.openStream())); String inputLine; while ((inputLine = in.readLine()) != null){ try{ curDate = df.parse(inputLine.substring(0, 8)); }catch(Exception e){ curDate = new Date(); } if(!curDate.before(strtDate) && !curDate.after(stpDate)) result_area.append(inputLine + "\n"); } in.close(); }catch(Exception e){ result_area.append("Error while reading URL! (" + e + ")\n"); } result_area.append("\n"); } //if(event.getKeyCode()... } //keyReleased... } //class StockReaderApplet