Start New Discussion within our Software Development Community

hi i am new to java applets...i am making an digital clock...this is my code...my prob is time doesn't change automatically....it has to be refreshed...pls see

package jas;

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


public class sd extends Applet implements Runnable {
String am_pm="Time is ";
    Thread t=null;
    int state;
boolean stopFlag;

   

    public void init() {
        setBackground(Color.PINK);
        setForeground(Color.BLUE);
}
        
 public void start()
        {
        Thread t= new Thread(this);
        stopFlag=false;
        t.start();
    }
    public void run(){
Calendar calendar = new GregorianCalendar();
        for(;;)
        {
         try{

        Thread.sleep(1500);


    int hour = calendar.get(Calendar.HOUR);
    int minute = calendar.get(Calendar.MINUTE);
    int sec= calendar.get(Calendar.SECOND);
    if(calendar.get(Calendar.AM_PM) == 0)
      am_pm = "AM";
    else
      am_pm = "PM";
    am_pm+=("Current Time : " + hour + ":"
+ minute + ":" + sec+ " " + am_pm);
    repaint();
    if(stopFlag)
break;
    }

        catch(InterruptedException e)
                {

        }

        }
    }
     public void stop(){
        stopFlag = true;
t = null;
}
    public void paint(Graphics g) {
g.drawString(am_pm, 150, 130);

    }
    
}

alright, your application is all right, except for two minor defects.

one, you only have your application reading time once, that's why it repaints the same time every time it repaints. you need to put your line 28 somewhere where it is run each time a repaint is needed. that is, inside your for loop. and, another problem is that your thread sleeps a second and a half, which basically means that every third second is not painted. hope this helps.

This article has been dead for over six months. Start a new discussion instead.