SoftwarePractice.org: Home | Courseware | Wiki | Archive

Clock.java

From SoftwarePractice.org

package ood.spring.wps.clock;

import java.applet.Applet; import java.awt.Font; import java.awt.Graphics; import java.text.SimpleDateFormat; import java.util.Date;

import javax.swing.JFrame;

/**

* The digital clock display responsible for keeping track of the current time.
* @author Andrew Minh Tran 02047912
*
*/

public class Clock extends Applet implements Runnable { private static final long serialVersionUID = 1L; private static final String TIME_FORMAT = "HH:mm:ss"; private static final int SLEEP_IN_MILLISECS = 1000; private final SimpleDateFormat sdf; private Font clockFont = new Font("Arial", Font.BOLD, 58); private Thread clockThread = null; private Date timeStarted; private long timeElapsed;

public Clock(Date time) { timeStarted = time; timeElapsed = 0; sdf = new SimpleDateFormat(TIME_FORMAT); }

public void start() { if (clockThread == null) { clockThread = new Thread(this, Clock.class.getName()); clockThread.start(); } }

public void stop() { clockThread = null; }

public void run() { while (Thread.currentThread() == clockThread) { try { timeElapsed += SLEEP_IN_MILLISECS; Thread.sleep(SLEEP_IN_MILLISECS); } catch (InterruptedException ie) {

} repaint(); } }

/** * @see Applet.paint(); */ public void paint(Graphics g) { g.setFont(clockFont); g.drawString(getTimeString(), 15, 60);

   }

/** * Converts the date provided into 24 hour format. * For example, 11:30:00 PM would be converted to * 23:30:00. * @param date * @return the time in 24 hour format. */ private String convertTimeToString(Date date) { String time = null;

if (date != null) { time = sdf.format(date); } return time; }

/** * Gets the current time in String format. * @return */ private String getTimeString() { Date currentTime = getTime(); String time = convertTimeToString(currentTime); return time; }

/** * Gets the current time. * @return */ public Date getTime() { Long time = timeStarted.getTime() + timeElapsed;

return new Date(time); }

public void setTime(Date date) { timeElapsed = 0; timeStarted = date; }

/** * Test purposes only. * @param args */ public static void main(String[] args) { Clock clock = new Clock(new Date()); clock.start(); JFrame frame = new JFrame(); frame.add(clock); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }

Personal tools