gvsu/cs621/proj1/ClockApplet.java
josh c5eb553073 cs621: proj1: ClockApplet added, completed
git-svn-id: svn://anubis/gvsu@10 45c1a28c-8058-47b2-ae61-ca45b979098e
2008-02-03 05:35:27 +00:00

89 lines
2.0 KiB
Java

import javax.swing.JApplet; // import class JApplet
import java.awt.Graphics; // import class Graphics
import java.awt.*;
/**
* This class provides an applet displaying the current time.
*/
public class ClockApplet extends JApplet
{
private Thread animator = null;
/**
* Called to stop the applet.
*/
public void stop()
{
if (animator != null)
animator.interrupt();
animator = null;
}
/**
* Method called to begin the applet.
*/
public void start()
{
if (animator == null)
{
animator = new Thread() {
public void run() {
updateTime();
}
};
animator.start();
}
}
/**
* The method run by the animator thread.
*/
public void updateTime()
{
try
{
while (!Thread.interrupted())
{
repaint();
Thread.sleep(500);
}
}
catch (InterruptedException e) { }
}
/**
* This function draws the applet's contents.
* @param g the graphics object to draw with
*/
public void paint( Graphics g )
{
Timestamp t = new Timestamp();
t.fillTimes();
String display = getDigitsAsString(t.hrs) + ":" +
getDigitsAsString(t.mins) + ":" +
getDigitsAsString(t.secs) + " " +
t.am_pm;
g.setColor(Color.white);
g.fillRect(0, 0, 150, 60);
g.setColor(Color.black);
g.drawString(display, 10, 50);
}
/**
* Helper method to convert an integer to a 0-padded string.
* @param i The integer to convert
* @return A string representing the integer, padded on the
* left by a '0' character if the integer was less than 10.
*/
protected String getDigitsAsString(int i)
{
String str = Integer.toString(i);
if (i < 10)
str = "0" + str;
return str;
}
}