How to display clock using Applet in Java



Problem Description

How to display clock using Applet?

Solution

Following example demonstrates how to display a clock using valueOf() methods of String Class. & using Calender class to get the second, minutes & hours.

import java.awt.*;
import java.applet.*;
import java.applet.*;
import java.awt.*;
import java.util.*;

public class ClockApplet extends Applet implements Runnable { 
   Thread t,t1;
   public void start() {
      t = new Thread(this);
      t.start();
   }
   public void run() { 
      t1 = Thread.currentThread();
      while(t1 == t) {
         repaint();
         try {
            t1.sleep(1000);    
         }
         catch(InterruptedException e){}
      }
   }
   public void paint(Graphics g) {
      Calendar cal = new GregorianCalendar();
      String hour = String.valueOf(cal.get(Calendar.HOUR));
      String minute = String.valueOf(cal.get(Calendar.MINUTE));
      String second = String.valueOf(cal.get(Calendar.SECOND));
      g.drawString(hour + ":" + minute + ":" + second, 20, 30);
   }
}

Result

The above code sample will produce the following result in a java enabled web browser.

View in Browser. 

The following is an another sample example to display clock using Applet.

import java.applet.*;  
import java.awt.*;  
import java.util.*;  
import java.text.*;  
  
public class javaApplication6 extends Applet implements Runnable {  
   Thread t1 = null;  
   int hours = 0, minutes = 0, seconds = 0;
   String time = "";
   
   public void init() {  
      setBackground( Color.green);  
   }  
   public void start() {
      t1 = new Thread( this );
      t1.start();
   } 
   public void run() {
      try {
         while (true) {
            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 d = cal.getTime();  
            time = formatter.format( d );
            
            repaint();  
            t1.sleep( 1000 ); 
         }  
      }  
      catch (Exception e) { }  
   } 
   public void paint( Graphics g ) {
      g.setColor( Color.blue );  
      g.drawString( time, 50, 50 );  
   }  
}  
java_applets.htm
Advertisements