IOException流在Gif上关闭
问题描述:
我试图在简单的JFrame上显示一个Gif。我创建了“LoadingGif”类,但在Gif出现后,我收到了一秒钟的错误消息java.io.IOException : Stream closed
,然后停止。IOException流在Gif上关闭
我把这个类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;
}
}
有谁知道为什么我得到这个流关闭?
在此先感谢!
答
我试着先简化你的示例代码。例如,我刚刚使用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是动画和没有任何错误显示。
在我的情况下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 = new ImageIcon(url); label = new JLabel(imageIcon);'标签/图标将异步加载图像(加载时可能会发生其他事情),而此代码if(f.isDisplayable()){f.dispose();'将只要框架可显示,就会导致JVM停止加载图像。我怀疑是这个问题。 1)为了更快地获得更好的帮助,请发布[MCVE]或[简短,独立,正确的示例](http://www.sscce.org/)。 2)获取图像的一种方法是通过[本问答](http://stackoverflow.com/q/19209650/418556)中的图像进行热链接。 –
本课是单身人士。我使用'LoadingGif.getInstance.runUI()'在我的main()的一开始就调用这个类,然后在最后我调用'LoadingGif.getInstance.stopLoading()' 事情是图像很好加载,而gif动画可能为0.5s,然后我得到了错误信息。 – Jooooris