Java IOException流在Gif上关闭
我试图在一个简单的JFrame上显示Gif。我创建了“LoadingGif”类,但在Gif出现一秒钟后,我收到了一条错误消息Java IOException流在Gif上关闭,java,swing,gif,ioexception,Java,Swing,Gif,Ioexception,我试图在一个简单的JFrame上显示Gif。我创建了“LoadingGif”类,但在Gif出现一秒钟后,我收到了一条错误消息java.io.IOException:Stream closed,然后它停止了 我使用加载gif.getInstance.runUI()调用该类,该类的源代码为: public class LoadingGif { private static LoadingGif instance = null; private JFrame f; priv
java.io.IOException:Stream closed
,然后它停止了
我使用加载gif.getInstance.runUI()调用该类,该类的源代码为:
public class LoadingGif {
private static LoadingGif instance = null;
private JFrame f;
private JLabel label;
private URL url;
private ImageIcon imageIcon;
private LoadingGif()
{
url = TraceaReq.class.getResource("/load.gif");
imageIcon = new ImageIcon(url);
label = new JLabel(imageIcon);
}
public void runUI()
{
f = new JFrame(RQTFGenDOORS.VERSION+" - Loading...");
f.getContentPane().add(label);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setResizable(false);
f.setVisible(true);
f.setAlwaysOnTop(true);
}
public void stopLoading(){
if(f.isDisplayable())
{
f.dispose();
}
}
public static LoadingGif getInstance()
{
if(instance == null)
{
instance = new LoadingGif();
}
return instance;
}
}
有人知道我为什么要关闭这条小溪吗
提前谢谢 我首先尝试简化您的示例代码。例如,我刚刚使用了GIF文件的硬编码路径(现在是硬编码的,以确保图像位置一切正常,类路径没有任何问题,等等)。我还使用了
LoadingGif
类的构造函数,而不是单例工厂
我的示例代码如下所示:
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class LoadingGif {
private JFrame frame;
private JLabel label;
private ImageIcon imageIcon;
private LoadingGif() {
imageIcon = new ImageIcon("/home/me/Temp/loading-gif/src/animated-penguin-gif-5.gif");
label = new JLabel(imageIcon);
}
public void runUI() {
frame = new JFrame("MyGif - Loading...");
frame.getContentPane().add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
frame.setAlwaysOnTop(true);
}
public static void main(String args[]) {
LoadingGif loadingGif = new LoadingGif();
loadingGif.runUI();
}
}
并且动画和显示没有任何错误
在我的例子中,GIF文件不是很大。安德鲁·汤普森(Andrew Thompson)已经说过,可能是在你的情况下,它非常大,需要一些时间才能加载。无论如何,您可以借助javax.swing.ImageIcon#getImageLoadStatus
方法检查图像是否已加载,然后检查返回的标志。对于java.awt.MediaTracker#COMPLETE
Javadoc说:
/**
* Flag indicating that the downloading of media was completed
* successfully.
* @see java.awt.MediaTracker#statusAll
* @see java.awt.MediaTracker#statusID
*/
public static final int COMPLETE = 8;
您如何使用/调用该类?
imageIcon=newimageicon(url);标签=新的JLabel(图像图标)
标签/图标将异步加载图像(加载时可能会发生其他情况),而此代码if(f.isDisplayable()){f.dispose();
将导致JVM在帧可显示时停止加载图像。我怀疑这就是问题所在。1)为了更快地获得更好的帮助,发布或。2)获取图像的一种方法例如,热链接到中看到的图像。这个类是一个单例。我在main()的最开始使用LoadingGif.getInstance.runUI()
,调用这个类,然后在最末尾调用LoadingGif.getInstance.stopLoading()
问题是图像加载良好,gif动画可能持续了0.5秒,然后我收到了错误消息。