我正在尝试将 GIF 文件显示到 JLabel。没问题,我加载 GIF 并将其设置为标签的图标。但现在我真的需要知道这一切何时结束,因为它必须起到过场动画的作用。我已经尝试过的是这个(GameScene 是一个自定义对象,但我知道 setIcon 有效,相信我):
private GameScene scene;
private ImageIcon _temp;
private ImageIcon toplay;
private Thread anim;
public Cutscene(ImageIcon gif, GameScene scene, int length){
this._temp = scene.getIcon();
this.toplay = gif;
this.scene = scene;
anim = new Thread(){
@Override
public void run(){
scene.setIcon(gif);
scene.repaint();
try {
Thread.sleep(length);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}
private void _s(){
scene.setSolidColor(false);
scene.setIcon(toplay);
scene.repaint();
}
public void play(){
_s();
anim.start();
}
public void await(){
try {
anim.join();
scene.setIcon(_temp);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
现在,我是否可以实现这一目标,而无需让整个程序 hibernate 指定的时间,然后继续执行其余代码并且完全不绘制 GIF 文件?
最佳答案
这是一个非常简单的示例,它仅适用于非循环 gif,如果您的 gif 重复,您必须测试 FRAMEBITS
请求之间的时间,并尝试确定是否可以检测循环点。
public class MonitoringLabel extends JLabel {
public MonitoringLabel(Icon image) {
super(image);
}
public void addActionListener(ActionListener listener) {
listenerList.add(ActionListener.class, listener);
}
public void removeActionListener(ActionListener listener) {
listenerList.remove(ActionListener.class, listener);
}
protected void fireActionPerformed() {
ActionListener[] listeners = listenerList.getListeners(ActionListener.class);
if (listeners.length > 0) {
ActionEvent evt = new ActionEvent(this, 0, "stopped");
for (ActionListener listener : listeners) {
listener.actionPerformed(evt);
}
}
}
@Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h) {
boolean finished = super.imageUpdate(img, infoflags, x, y, w, h);
if (!finished) {
fireActionPerformed();
}
return finished;
}
}
上面的类提供了一个 ActionListener
,当图像“完成”加载时触发(当要播放的动画中没有新帧时触发 - 重复的 gif 永远不会返回假
)
如果需要,您可以使用不同的监听器接口(interface),我只是将其放在一起作为示例。
我选择覆盖imageUpdate
的原因是因为JLabel
在绘制图像时已经充当图像的ImageObserver
,这我们可以使用 JLabel
的强大功能,而不必担心手动绘制 gif ...是的,我已经做到了,这很痛苦
关于java - 了解 GIF 何时播放完毕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42077591/