/* Class supporting a thread maintaining timer */ import java.awt.*; public class WatchThread extends Thread { protected long lastTime; // accumulated time before latest push of start button protected Label timeField; // Display for timer protected long startTime; // Time start button is pushed protected long time = 0; // Total time on timer protected boolean running = true; // Whether timer is to be running (or paused) // Create thread with name "watch" and record TextField for display. public WatchThread(Label timeField) { super("watch"); this.timeField = timeField; } // Method running timer. Suspends until start button is pushed. Suspend again // if pause button is pushed. Displays total running time since timer initialized. public void run() { while(true) { suspend(); running = true; startTime = System.currentTimeMillis(); lastTime = time; while (running) { time = lastTime + (System.currentTimeMillis() - startTime); doze(10); timeField.setText(timeString(time)); } } } // Set running to false in response to pause button. public void pause() { running = false; } // Clear total time - reset to zero. public void clear() { time = 0; timeField.setText("00 : 00 : 00"); lastTime = 0; startTime = System.currentTimeMillis(); } // Convert time to a string ready to be displayed String timeString(long time) { long hundredths, seconds, minutes; hundredths = Math.round(Math.floor(time/10)) % 100; seconds = Math.round(Math.floor(time/1000)) % 60 ; minutes = Math.round(Math.floor(time/(1000*60))); return digits(minutes) + " : " + digits(seconds) + " : " + digits(hundredths); } // Convert time to two letter string String digits(long time) { String dig = Long.toString(time); dig = "00" + dig; return dig.substring(dig.length()-2); } // Pause for interval milliseconds public void doze(int interval) { try { sleep(interval); } catch (InterruptedException e) {} } }