// TEST CODE FOR CONTINUOUS DISPLAY OF DATE AND TIME /* First we get the time and date from from the Date class and store it in a Gregorian Calendar object. We then use the Calendar class to retrieve the date and time fields from the Gregorian calendar object. We use a thread to display the time on the status bar. To achieve updated display, we let the thread sleep for a while. When it wakes up, it resumes displaying the time. */ /* To run, save the program as DateTest.java and compile using the command javac DateTest.java. On the same folder, create a html file and insert the following tags: . Run the html file using the command appletviewer DateTest.html. */ import java.util.Date; import java.util.Calendar; import java.util.GregorianCalendar; import javax.swing.*; // Extend JApplet and implement the Runnable interface public class DateTest extends JApplet implements Runnable { JLabel lblNote; Thread datimeThread; Date date; GregorianCalendar calendar; String strDate, strTime, strStatus; public void init() // Start the thread here { lblNote = new JLabel("Check current time on status bar!"); getContentPane().add(lblNote); datimeThread = new Thread(this); datimeThread.start(); } /* Must override java.lang.Thread's run method if Thread is extended or Runnable interface implemented. */ public void run() { while(datimeThread != null) { displayTime(); try { datimeThread.sleep(1000); } catch(InterruptedException e) { showStatus("Thread Interrupted"); } } } public void displayTime() // Extract and display time { date = new Date(); calendar = new GregorianCalendar(); calendar.setTime(date); strTime = calendar.get(Calendar.HOUR) + ":" + calendar.get(Calendar.MINUTE) + ":" + calendar.get(Calendar.SECOND); strDate = (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.DATE) + "/" + calendar.get(Calendar.YEAR); strStatus = strTime + " " + strDate; showStatus(strStatus); } } /* Experiment by varying the sleeping time of thread say make it 3000 or 5000 milliseconds. Recompile and re-run the applet to see the effect. */