移动圆圈在小程序中闪烁

时间:2014-12-27 00:32:33

标签: java swing animation applet

我创建了一个带有红色圆圈的小程序,可以从左上角移动到右下角。即使我将圆圈生成为缓冲图像,但这会发生但整个帧都会闪烁。这是代码:

import java.awt.Color;  
import java.awt.Graphics;  
import java.awt.Image;  
import java.awt.image.BufferedImage;  
import javax.swing.JApplet;  

public class MovingCircleApplet extends JApplet implements Runnable {

private int x_pos;
private int y_pos;
private int radius;
private Thread circle;

@Override
public void init() {
    x_pos  = 20;
    y_pos  = 40;
    radius = 10;
    setSize(245,265);
    circle = new Thread(this);
    circle.start();
}

@Override
public void run() 
{
    while (true) 
    {
        // redraw
        repaint();

        try
        {
            // sleep thread for 20 milliseconds
            Thread.sleep(20);
        }
        catch (InterruptedException e)
        {
            System.out.println("Terminated prematurely due to interruption");
        }

        // move circle to lower right corner
        if (x_pos < 225) 
        {
            x_pos++;
            y_pos++;
        }
        // restart at top right corner
        else 
        {
            x_pos = 20;
            y_pos = 40;
        }           
    }
}  
@Override
public void paint(Graphics g)
{
    super.paint(g);
    g.drawImage(getFrame(), 0, 0, null);
}

private Image getFrame() 
{
    // Buffered image to prevent flickering
    BufferedImage img = new BufferedImage(getWidth(),getHeight(),
            BufferedImage.TYPE_3BYTE_BGR);
    Graphics g = img.getGraphics();
    // white background
    g.setColor(Color.WHITE);
    g.fillRect(0,0,getWidth(),getHeight());
    // red circle
    g.setColor(Color.RED);
    g.fillOval(x_pos-radius, y_pos-radius, 2*radius, 2*radius);
    //
    g.dispose();
    return img;
}
}

0 个答案:

没有答案