0

I have a swing component that displays an animation. Frames of animation are computed on the fly (in a BufferedImage) and displayed at around 30fps.

The problem is that every now and then, it produces half a frame at a time - giving a very obvious discontinuity in the output (which in the test case given below should just flash black/white).

Can anyone tell me what causes the glitch and how to fix it?

PLEASE BE WARNED, RUNNING THIS CODE WILL GENERATE RAPIDLY FLASHING LIGHTS

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;

class Animation extends JComponent {
    FrameSource framesource;
    public Animation(FrameSource fs)
    {
        this.framesource = fs;
        setDoubleBuffered(true); 
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    framesource.computeNextFrame();
                    Animation.this.repaint();
                    try {Thread.sleep(30);} catch (InterruptedException e) {}
                }
            }
        }).start();
    }
    public Dimension getPreferredSize() {return new Dimension(500,500);}
    public void paintComponent(Graphics g) {
            g.drawImage(framesource.getCurrentFrame(), 0,0,null);
    }
}
class FrameSource
{
    private BufferedImage currentframe;
    public BufferedImage getCurrentFrame() {return currentframe;}
    int frameCount = 0;
    public void computeNextFrame()
    {
        BufferedImage nextFrame = new BufferedImage(500,500,BufferedImage.TYPE_INT_RGB);
        for (int x=0;x<500;x++)
            for (int y=0;y<500;y++)
            {
                nextFrame.setRGB(x, y, (frameCount%2==0)?16777215:0);
            }
        frameCount++;
        currentframe = nextFrame;
    }
}
public class Flickertest {
        public static void main(String[] args) 
        {
            JFrame frame = new JFrame();
            FrameSource fs = new FrameSource();
            Animation a = new Animation(fs);
            frame.getContentPane().add(a);
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
}
Sideshow Bob
  • 4,566
  • 5
  • 42
  • 79
  • I don't notice any obvious discontinuity, but then again I don't want to stare at it for too long. I'm running JDK7 on Windows 7. – camickr Oct 21 '14 at 20:31
  • Try [this](http://stackoverflow.com/a/25043676/230513) or [this](http://stackoverflow.com/a/16880714/230513). – trashgod Oct 21 '14 at 20:34
  • It could be a hardware/OS issue – MadProgrammer Oct 21 '14 at 21:36
  • Ok I tried on another machine - looks like it is a hardware/OS issue. @camickr I see what you mean about staring at it - it's a lot more intense looking for things that aren't there - they were visible straight away on my xp box! – Sideshow Bob Oct 22 '14 at 10:42

0 Answers0