Search code examples
javagraphicsapplet

Why does clearRect() method not clear an area on the canvas?


I wrote a Java applet that prints a text on the canvas at the same position after getting updated in every iteration of a loop. The text value changes and the output is correct but the clearRect() method I call in the loop to clear the area of the text before printing out each time doesn't work and the text gets overwritten. I can see the output up to 2-3 iterations but then it's not readable. The applet actually performs a countdown and displays the time in HH : MM : SS format. Below is my code. Please predict the cause of this and/or correct it:

/* Only the section of the code I'm having problems in is included */

while (t>=0) {
    //int t stores total time in seconds
    int h=(t/3600);
    int m=((t%3600)/60);
    int s=((t%3600)%60);
    str=h+" : "+m+" : "+s;
    /* String str holds data to be displayed, i.e., time in HH : MM : SS format */
    g.clearRect(20,200,150,30);
    g.drawString(str,20,200);
    try{
        Thread.sleep(1000); //elapses 1 second
    }
    catch(Exception e) {}
    t=t-1;
}

Solution

  • use drawRect with a color instead of clearRect. just like how @ControlAltDel explained it. I am not sure if that code above is located in your paint or run. I would still recommend to have runnable method instead of drawing it in a loop. Similar to this link. Good luck