【问题标题】:ImageIO.Read not working most of the time?ImageIO.Read 大部分时间都不起作用?
【发布时间】:2012-07-04 14:55:33
【问题描述】:

我想使用 swing 显示来自 URL Java 的图像。我使用此代码:

BufferedImage pic = ImageIO.read(new URL("http://www.swpc.noaa.gov/SWN/g_curr.gif"));
JLabel label1 = new JLabel(new ImageIcon(pic));
label1.setBounds(200,28,32,12);
jp.add(label1); //jp is a JPanel.

大约有四分之一的时间有效。其他时候什么都不显示,也不抛出异常。

【问题讨论】:

  • 你确定是ImageIO.read(...)的错吗?我怀疑情况是否如此。也许这是更基本的东西,例如您在标签上设置的界限?
  • 服务器是否正常工作,最好不要将ImageIO放到看台上,而是询问服务器,它是否正常工作?
  • 请看看这个example,如果我的电脑工作正常,因为它是服务器,你肯定可以看到图像。

标签: java swing jlabel bufferedimage javax.imageio


【解决方案1】:

我建议您创建一个JFrame,然后将您的JPanel 添加到其中。

这是我尝试过的......

  //necessary imports over here 

    class Test extends javax.swing.JFrame 
  {
     public static void main(String args[]) throws MalformedURLException, IOException 
   {

  Test inst = new Test();
  inst.setLocationRelativeTo(null);
  inst.setVisible(true);
  JPanel jp=new JPanel();   
  BufferedImage pic = ImageIO.read(new URL("http://www.swpc.noaa.gov/SWN/g_curr.gif"));
  JLabel label1 = new JLabel(new ImageIcon(pic));

  jp.add(label1);
  jp.setVisible(true);
  inst.add(jp);
  inst.getContentPane().setLayout(new FlowLayout());
  inst.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
  inst.pack();
  inst.setSize(300,300);

    }
}

这段代码效率不高,但至少可以为您提供输出。

希望对你有帮助

【讨论】:

  • 你为什么也打电话给setBounds(...)?如果您要提供建议,至少要向原始海报展示如何正确使用布局管理器。
  • 是的,我同意你的看法。我应该在我的代码中省略它。感谢您指出。在以后发布答案时,我会记住这些事情。
猜你喜欢
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多