public class circleGame extends JApplet{
private boolean animationDone;
private ArrayList<Circle> circles = new ArrayList<Circle>();
public void init(){
createCircles(10);
new Thread(){
@Override
public void run(){
while(!animationDone){
updateAnimation();
repaint();
delayAnimation();
}
}
}.start();
}
public void createCircles(int amount){
for(int i=0; i<amount; ++i){
circles.add(new Circle());
}
}
public void delayAnimation(){
try {
Thread.sleep(30);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void updateAnimation(){
for(Circle circle: circles){
circle.x+= circle.deltaX/20.0;
circle.y+= circle.deltaY/20.0;
}
}
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for(Circle circle: circles){
g2d.setColor(circle.color);
int xPosition = (int) (circle.x-circle.radius);
int yPosition = (int) (circle.y-circle.radius);
int diameter = circle.radius*2;
g2d.fillOval(xPosition, yPosition,
diameter, diameter);
}
}
我正在尝试创建一定数量的圆圈,并使它们能够设置动画,而不会像当前代码那样拖动或拖尾颜色。圆圈应该在JApplet上流畅地移动,而不会拖动颜色
答案 0 :(得分:3)
这样做的一个简单方法是通过添加
来清除之前绘制的所有内容g2d.clearRect(0, 0, getWidth(), getHeight());
在paint
方法的开头。不过,我建议您使用专用的JComponent
来绘制圆圈并覆盖它的paintComponent
方法,而不是paint
。这将为您解决此问题,并防止小程序闪烁。
class CirclesComponent extends JComponent {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// insert content of your paint method here
}
}
通过在this.getContentPane().add(new CirclesComponent());
方法的开头添加init
并将原始paint
方法移除,将其添加到您的小程序。