首页 > 解决方案 > 有没有比在 Java 中使用 imageIcon 数组更性能友好的方式来遍历动画的图像?

问题描述

我正在尝试在 JPanel 上为我正在构建的游戏制作海鸥图像的动画。动画效果很好,它看起来像我想要的那样,但是当我单击播放按钮将卡片切换到下一个 JPanel 时,(有一个由包含此面板的 JFrame 控制的播放按钮将卡片更改为另一个 JPanel,这个动画运行时滞后)它在动画运行时滞后。有没有比像我正在做的那样循环通过 ImageIcon[] 来运行我的动画的更性能友好的方式?

public class StartPanel extends JPanel implements ActionListener{
    
    Image gull;
    
    Timer timer;
    ImageIcon[] seagullAnimation = new ImageIcon[9];
    int counter = 0;
   

StartPanel(){
    seagullAnimation[0] = new ImageIcon(getClass().getResource("gullBlink0.png"));
    //Here I add the rest of the images in the same fashion

    timer = new Timer(13, this);
    timer.start();
    setPreferredSize(new Dimension(500,500));

}
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    //Iterates through the Gull Blink images and set the proper image
    if(counter >=8){
        counter = 0;
        timer.stop();
            try {    
                //Randomizes sleep times to make blink look natural
                Thread.sleep((long) (Math.random() * 5000));
                timer.start();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        
 
    } else {
        counter++;
    }
    gull = seagullAnimation[counter].getImage();

    g.drawImage(gull,10,-450, this);

}

@Override
public void actionPerformed(ActionEvent e) {
    repaint();
}}

标签: javaimageswinganimationpaintcomponent

解决方案


修复了滞后。删除了使 Event Dispatch 线程休眠的代码,这似乎导致了延迟,并使用计时器来处理动画之间的暂停。

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    setGullFrame();
    gull = seagullAnimation[counter].getImage();
    g.drawImage(gull,10, -450, this);


public void setGullFrame(){
    
    if(counter >=8){
        counter = 0;
        timer.stop();
        timer.setInitialDelay((int) (Math.random() * 5000));
        timer.start();

    } else {
        counter++;
    }

}

推荐阅读