当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Moving circle flashing in applet

问题描述:

I have created an applet with a red circle to move from top left to bottom right. That occurs but the whole frame is flickering even though I generate the circle as a buffered image. Here is the code:

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;

}

}

分享给朋友:
您可能感兴趣的文章:
随机阅读: