【发布时间】:2017-11-02 17:20:05
【问题描述】:
我试图在一个简单的 JFrame 上显示一个 Gif。我创建了“LoadingGif”类,但在 Gif 出现后一秒钟我收到了这个错误消息java.io.IOException : Stream closed,然后它就停止了。
我用LoadingGif.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;
}
}
有人知道我为什么关闭了这个流吗?
提前致谢!
【问题讨论】:
-
你如何使用/调用这个类?
-
imageIcon = new ImageIcon(url); label = new JLabel(imageIcon);标签/图标将异步加载图像(加载时可能会发生其他事情),而此代码if(f.isDisplayable()) { f.dispose();将导致 JVM 停止加载图像框架是可显示的。我怀疑这是问题所在。 1) 为了尽快获得更好的帮助,请发布minimal reproducible example 或Short, Self Contained, Correct Example。 2) 例如,获取图像的一种方法是热链接到在this Q&A 中看到的图像。 -
这个类是一个单例。我在 main() 的开头使用
LoadingGif.getInstance.runUI()调用这个类,然后在最后我调用LoadingGif.getInstance.stopLoading()问题是图像加载良好,gif 动画可能持续 0.5 秒,然后我收到错误消息。
标签: java swing gif ioexception