Here’s an example of a digital clock in Java applet:
import java.applet.*; import java.awt.*; import java.util.*; public class DigitalClock extends Applet implements Runnable { Thread t = null; int hours = 0, minutes = 0, seconds = 0; String timeString = ""; public void init() { setBackground(Color.black); } public void start() { t = new Thread(this); t.start(); } public void run() { while (true) { try { Thread.sleep(1000); Calendar cal = Calendar.getInstance(); hours = cal.get(Calendar.HOUR_OF_DAY); if (hours > 12) hours -= 12; minutes = cal.get(Calendar.MINUTE); seconds = cal.get(Calendar.SECOND); SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss"); Date date = cal.getTime(); timeString = formatter.format(date); repaint(); } catch (InterruptedException e) { System.out.println("Thread error: " + e.getMessage()); } } } public void paint(Graphics g) { g.setColor(Color.green); g.drawString(timeString, 50, 50); } }
This code creates a DigitalClock
class that extends the Applet
class and implements the Runnable
interface. The init()
method sets the background color of the applet to black.
The start()
method creates a new thread and starts it. The run()
method is executed by the thread and updates the time every second using the Calendar
and SimpleDateFormat
classes. The time is then formatted and stored in the timeString
variable, which is used to display the time in the paint()
method.
The paint()
method sets the color to green and draws the timeString
on the applet at the position (50, 50).
To use this applet, you can create an HTML file that embeds the applet:
<html> <head> <title>Digital Clock</title> </head> <body> <applet code="DigitalClock.class" width="200" height="100"> </applet> </body> </html>
This HTML code creates an applet that runs the DigitalClock
class with a width of 200 pixels and a height of 100 pixels.