Tuesday, April 24, 2007

Build a digital clock with Java

Here is a piece of code to build a Java clock applet that uses threads, gets the data for time automatically and is not interrupted if you click something else on the web page. There are some comments around the code to help you understand what's happening. Program build and tested with Netbeans 5.5. If I find a way, I will upload the applet here to see it running in real time!
import java.awt.*;
import javax.swing.*;
import java.util.Date;
import java.text.DateFormat;
// builds the clock
class MyClock extends JApplet implements Runnable
{ private Thread myThread; // the thread
private JLabel clock; // the label
private final int interval = 1000; // time in
// milliseconds
public void init()
{ clock = new JLabel("", SwingConstants.CENTER);
clock.setFont (new Font ("Verdana", Font.BOLD,
28));
clock.setBackground(Color.BLUE());
clock.setForeground(Color.WHITE);
clock.setOpaque(true);
getContentPane().add(clock);
setSize(250, 100);
}
public void start()
{ if (myThread == null)
{ myThread = new Thread(this, "clock");
myThread.start();
}
} // start

public void run()
{
while (myThread == Thread.currentThread())
{ // gets data for the clock

Date time = new Date();
clock.setText(DateFormat.getTimeInstance
(DateFormat.MEDIUM).format(time));
try
{ //thread sleeps for a sec
myThread.sleep(interval);
}
catch (InterruptedException e) {}
}
} // run
public void stop()
{
myThread = null;
}
}

1 comment:

merooo0ooo said...

hi
there'r error in this line
clock.setBackground(Color.BLUE());
can'nt find blue method i don'nt know why?