-3
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 上流畅地移动而不拖动颜色

4

1 回答 1

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

于 2013-09-09T08:44:04.837 回答