import java.applet.*; import java.awt.*; import java.awt.event.*; import java.util.*; /* When the user clicks on the Go button, any text in the textarea is processed. Each line of text is assumed to represent a command to draw a line on the LineCanvas component of the applet. Example input: LINE (100,100) (500,150) LINE (100,300) (500,250) LINE 100 100 100 300 */ public class LineApplet extends Applet implements ActionListener { TextArea ta; LineCanvas theLineCanvas; Button goButton; int x1, y1, x2, y2; public void init() { setLayout(new BorderLayout()); ta = new TextArea(5,20); theLineCanvas = new LineCanvas(); goButton = new Button("Go"); theLineCanvas.setSize(300,200); theLineCanvas.setBackground(Color.yellow); add(ta, BorderLayout.NORTH); add(theLineCanvas, BorderLayout.CENTER); add(goButton, BorderLayout.SOUTH); goButton.addActionListener(this); } public void actionPerformed(ActionEvent e) { if (e.getSource() == goButton) { theLineCanvas.clear(); StringTokenizer lines = new StringTokenizer(ta.getText(), "\n"); while (lines.hasMoreTokens()) { String line = lines.nextToken(); try { StringTokenizer lt = new StringTokenizer(line, "() ,;"); String command = lt.nextToken(); if (command.equals("CLEAR")) { theLineCanvas.clear(); continue; } if (! (command.equals("LINE"))) { error("Unknown command: " + command); continue; } if (isInt(lt.nextToken())) { x1 = inputInt; } else continue; if (isInt(lt.nextToken())) { y1 = inputInt; } else continue; if (isInt(lt.nextToken())) { x2 = inputInt; } else continue; if (isInt(lt.nextToken())) { y2 = inputInt; } else continue; theLineCanvas.addLine(x1, y1, x2, y2); } catch (Exception exc) { error("LineApplet expected a proper LINE command but got: " + line); } } } } int inputInt; boolean isInt(String token) { boolean returnVal = true; try { inputInt = (new Integer(token)).intValue(); } catch(NumberFormatException nfe) { error("LineApplet expected an integer but found: " + token); returnVal = false; } return returnVal; } void error(String msg) { theLineCanvas.setString(msg); System.out.println(msg); } }