I have a class for which I am not happy with the animation. I've simplified it to a simple square moving accross the screen. My problem is that the screen doesn't clear and so instead of a moving box, I get a thick line. I've tried a few attempts to fix this below. I've read about double-buffering and have tried to implement this, but something is missing. Can you help point out my issue?
Original class (a moving box is a line):
import java.awt.*; import java.awt.geom.*; import javax.swing.*; public class RightPane extends JApplet implements Runnable { int frame; Thread animator; public void start() { frame = 0; animator = new Thread(this); animator.start(); } public void run() { long tm = System.currentTimeMillis(); while(Thread.currentThread() == animator) { repaint(); try { tm += 50; // 50 ms iteration rate Thread.sleep(Math.max(0, tm - System.currentTimeMillis() ) ); } catch (InterruptedException e) { break; } frame++; if (frame == 100) // Freeze the animation here this.stop(); } } public void stop() { animator = null; } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; Dimension d = this.getSize(); g2.setPaint( Color.red ); g2.fill ( new Rectangle2D.Double( d.width*frame/100, d.height*frame/100, 10, 10) ); } }
This was my first attempt to fix this. It does help, but causes significant flashing:
public void paint(Graphics g) { super.paint(g); // Adding this line will cause flashing, // but at least everything clears Graphics2D g2 = (Graphics2D) g; Dimension d = this.getSize(); g2.setPaint( Color.red ); g2.fill ( new Rectangle2D.Double( d.width*frame/100, d.height*frame/100, 10, 10) ); }
Implementing the update() function was my second attempt to fix this. This is how I read to implement double-buffering. Unfortunately, it has no effect and I'm not sure what's wrong:
private Image dbImage; private Graphics dbg; public void update(Graphics g) { if (dbImage == null) { dbImage = createImage (this.getSize().width, this.getSize().height); dbg = dbImage.getGraphics(); } dbg.setColor (getBackground ()); dbg.fillRect (0, 0, this.getSize().width, this.getSize().height); dbg.setColor (getForeground()); paint (dbg); g.drawImage (dbImage, 0, 0, this); }