CHECK MY LAST POST FOR A BETTER CODE EXAMPLE
Hello,
I tried to draw a game on an applet and got huge flickering. The way I am drawing is:
I create an off-screen image of applet size, get its graphics, draw the objects on it I want to display with drawMaze and drawScore methods and in the end draw that off-screen image on the applet.
The program updates the image with thread. I simply put repaint() in the thread and sleep for a particual delay time. This way I get very big flickering.
public void run() { long timeBefore = System.currentTimeMillis(); Thread thread2 = Thread.currentThread(); while(thread == thread2) { repaint(); long timeDifference = System.currentTimeMillis() - timeBefore; int sleep = gameDelay - (int)timeDifference; if(sleep < 0) sleep = 2; try { thread.sleep(sleep); } catch(InterruptedException ex) { ex.printStackTrace(); } timeBefore = System.currentTimeMillis(); } }
After looking at some examples I notice another way of "repaint'ing", which looks like this:
public void run() { Graphics g = getGraphics(); long timeBefore = System.currentTimeMillis(); Thread thread2 = Thread.currentThread(); while(thread == thread2) { paint(g); long timeDifference = System.currentTimeMillis() - timeBefore; int sleep = gameDelay - (int)timeDifference; if(sleep < 0) sleep = 2; try { thread.sleep(gameDelay); } catch(InterruptedException ex) { ex.printStackTrace(); } timeBefore = System.currentTimeMillis(); } }
I tried it and it worked. No flickering at all.
So I want to understand: why this way there is no flickering? What is the difference between calling repaint() and paint(g) methods? Why repaint() produces flickering and paint(g) not? Doesn't repaint() just simply calls paint() method?