我正在创建一个 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");
虽然“drawn”正在控制台上打印出来,但爆炸 gif 没有加载。我检查了文件名,它是正确的。但是,我确实在我的代码中的其他地方使用了相同的 gif 并且它在那里工作,那么有什么东西可以防止在 Java 中两次使用 gif 吗?
这是我的整个paintComponent()方法:
super.paintComponent(g);
setfocusable(true);
requestFocus();
background = new ImageIcon("bg.png").getImage();
g.drawImage(background,-6,700,null); //background of JPanel
if (!hit) g.drawImage(plane,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(),this); //doesn't work
System.out.println("drawn"); //printed
}
title = new ImageIcon("title.png").getImage(); //transparent,is drawn
g.drawImage(title,-9,20,218,null);
title2 = new ImageIcon("title2.png").getImage(); //transparent,is drawn
g.drawImage(title2,10,245,670,null);
我已经检查了 title 和 title2,它们是透明的,这意味着应该可以看到爆炸。我什至在这两个图像下方尝试了它,但仍然看不到爆炸。我也在这个面板上使用 JButtons 和 KeyListeners。
如果我应该添加任何其他内容,请告诉我,并提前感谢您!