问题描述
我正在尝试在 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();
}}
解决方法
修复了延迟。删除了使事件调度线程休眠的代码,这似乎导致了延迟,并使用计时器来处理动画之间的暂停。
@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++;
}
}