java - 有没有比在 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();
}}
解决方案
修复了滞后。删除了使 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++;
}
}
推荐阅读
- firebase - Cloud firestore - 按嵌套数据排序
- pyspark - Pyspark 多个 JOINS 列 <> 行值:减少操作
- python - 如何在 Django 中获取购物车总金额?
- django - 我如何使用 DRF 序列化程序来获取以下 api 结构?
- android - 为什么我的布局看起来像这样?这是我的 XML 文件
- asp.net - 谷歌地图 API 方向服务重定向到 JSON 信息,但我如何让它在手机中打开地图应用程序?
- flutter - Flutter for loop 导致加载动画延迟
- javascript - 使用 appendchild 在 JavaScript 中将字符串转换为 DOM 节点(ul/li)
- java - 在数据库中搜索手机号码
- c++ - 返回我的数组索引号的两个总和(C++ 蛮力)问题