import java.awt.*; import java.awt.event.*; public class Timer implements Runnable { Thread timer; int counter = 0; TextField text; public Timer() { Frame f = new Frame("Timer demo"); f.setLayout(new GridLayout(2,0)); f.setResizable(false); // Create three event listening objects, private class Command startCmd = new Command(Command.START, this); Command stopCmd = new Command(Command.STOP, this); Command resetCmd = new Command(Command.RESET, this); // Assign a listener to the frame (window) f.addWindowListener(stopCmd); Panel p = new Panel(); Button b; // Create three buttons, assigning each a listener p.add(b = new Button("Start")); b.addActionListener(startCmd); p.add(b = new Button("Stop")); b.addActionListener(stopCmd); p.add(b = new Button("Reset")); b.addActionListener(resetCmd); f.add(p); // Set up a TextField for displaying results text = new TextField(" 00 ", 4); text.setEditable(false); text.setFont(new Font("Helvetica", Font.BOLD, 40)); f.add(text); f.pack(); f.show(); } public void Do (int id) { switch (id) { case Command.START: timer.resume(); break; case Command.STOP: timer.suspend(); break; case Command.RESET: counter = 0; text.setText(" 00 "); break; } } public void run() { while (true) { try {Thread.sleep(500);} // Should be 1000 catch (InterruptedException e) {}; counter += 1; if (counter == 100) counter = 0; // Trick way to format string as two digits text.setText(" " + counter/10 + counter%10 + " "); } } static public void main(String args[]) { Timer app = new Timer(); app.timer = new Thread(app); app.timer.start(); } } class Command extends WindowAdapter implements ActionListener { static final int START = 0; static final int STOP = 1; static final int RESET = 2; int id; Timer s; public Command(int id, Timer s) { this.id = id; this.s = s; } public void actionPerformed(ActionEvent e) { s.Do(id); } public void windowClosing(WindowEvent e) { System.exit(0); } }