1

I am making a simple digital clock. I want to remove flicker from when program runs. I tried different sleep time but it doesn't help.

public class DigitalClock extends Applet implements Runnable{

Thread t=null;
int hrs=0, min=0, sec=0;
String tString="";
public DigitalClock(){
    //TODO add required code
    init();
}

public void init() {
    // TODO Auto-generated method stub
    setBackground(Color.BLACK);
}

public void start(){
    t=new Thread(this);
    t.start();
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    DigitalClock dc=new DigitalClock();
    JFrame f=new JFrame("Digital Clock");
    f.setSize(300, 300);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(dc);
    dc.start();
    f.setVisible(true);
}

@Override
public void run() {
    // TODO Auto-generated method stub
    try {
        while(true){
            Calendar cal=Calendar.getInstance();
            hrs=cal.get(Calendar.HOUR_OF_DAY);
            min=cal.get(Calendar.MINUTE);
            sec=cal.get(Calendar.SECOND);
            tString=hrs+":"+min+":"+sec;
            repaint();
            Thread.sleep(40);
        }
    } catch (Exception e) {
        // TODO: handle exception
    }
}
public void paint(Graphics g){
    g.setColor(Color.white);
    g.drawString(tString, 50, 50);
}

}

How do i use paintComponent method. and will it help to reduce flicker?

  • 1
    Why do you need to repaint 25 times per second? – Jim Garrison Jun 19 '16 at 06:07
  • I want to add stopwatch and timer in the same app. So how do i reduce flicker while keeping same interval. – Niraj Rajan Jun 19 '16 at 15:10
  • 1) Why code an applet? If it is due to the teacher specifying it, please refer them to [Why CS teachers should **stop** teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) See [Java Plugin support deprecated](http://www.gizmodo.com.au/2016/01/rest-in-hell-java-plug-in/) and [Moving to a Plugin-Free Web](https://blogs.oracle.com/java-platform-group/entry/moving_to_a_plugin_free). .. – Andrew Thompson Jun 20 '16 at 05:42
  • .. 3) Why use AWT? See [this answer](http://stackoverflow.com/questions/6255106/java-gui-listeners-without-awt/6255978#6255978) for many good reasons to abandon AWT using components in favor of Swing. – Andrew Thompson Jun 20 '16 at 05:42

1 Answers1

1

Use a javax.swing.Timer instead of your sleep loop.

user207421
  • 305,947
  • 44
  • 307
  • 483