【发布时间】:2021-07-15 04:14:49
【问题描述】:
我正在创建一个 Java 游戏,在这个游戏中,我有一个可以由用户移动的飞机,但是如果飞机撞到任何一侧,它应该会爆炸——这意味着那个位置应该会发生爆炸.我使用了诸如:Why gif animation doesn't animate when using it in paintComponent()? 和其他链接来了解如何为 gif 设置动画,但是,我的代码不起作用。
以下是相关代码:
ImageIcon ii = new ImageIcon(this.getClass().getResource("explosion.gif"));
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(ii.getImage(), planeX, planeY, this);
System.out.println("drawn");
虽然“绘制”正在控制台上打印出来,但爆炸 gif 不会加载。我检查了文件名,它是正确的。但是,我确实在我的代码中的其他地方使用了相同的 gif,并且它在那里工作,那么有什么东西可以防止在 Java 中使用两次 gif 吗?
这是我的整个 paintComponent() 方法:
super.paintComponent(g);
setFocusable(true);
requestFocus();
background = new ImageIcon("bg.png").getImage();
g.drawImage(background, -6, 0, 700, 700, null); //background of JPanel
if (!hit) g.drawImage(plane, planeX, planeY, planeLen, planeHei, null); //only draw plane if not exploded
else if (count == 0)
{
ImageIcon ii = new ImageIcon(this.getClass().getResource("explosion.gif"));
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(ii.getImage(), planeX, planeY, this); //doesn't work
System.out.println("drawn"); //printed
}
title = new ImageIcon("title.png").getImage(); //transparent, is drawn
g.drawImage(title, -9, 20, 700, 218, null);
title2 = new ImageIcon("title2.png").getImage(); //transparent, is drawn
g.drawImage(title2, 10, 245, 670, 20, null);
我检查了title和title2,它们是透明的,这意味着应该可以看到爆炸。我什至在这两张图片下面都试过了,爆炸仍然不可见。我也在这个面板上使用 JButtons 和 KeyListeners。
如果我应该添加任何其他内容,请告诉我,并提前感谢您!
【问题讨论】:
-
不在您的环境中进行编码,但如果复制的作品听起来像是只需要重新启动动画,可能与此 Animated gif only loops once in Chrome and Firefox 相关...如果没有扩展,请尝试使用带有扩展名的 GIF复制。
标签: java graphics gif graphics2d