2013-02-10 56 views
1

我试图创建一个浮动对话框,其中包含一个加载器gif图像和一些文本。我有下面的类:如何将ImageIcon添加到JDialog中?

public class InfoDialog extends JDialog { 
    public InfoDialog() { 
     setSize(200, 50); 
     setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); 
     setUndecorated(true); 
     setLocationRelativeTo(null); 

     URL url = InfoDialog.class.getClassLoader().getResource("loader.gif"); 
     ImageIcon loading = new ImageIcon(url); 
     getContentPane().add(new JLabel("Logging in ... ", loading, JLabel.CENTER)); 
    } 
} 

然而,当我打电话:显示

InfoDialog infoDialog = new InfoDialog() 
    infoDialog.setVisible(true); 

一个空的对话框。 ImageIcon和标签不显示在对话框中。

我在这段代码中做了什么错误?

非常感谢。

+2

如果您停止添加.gif文件,它至少会显示文本?是否抛出任何异常?这对我来说很好。 – BeRecursive 2013-02-10 18:35:58

+0

您在EDT显示infoDialog? – 2013-02-10 19:06:40

+0

还可以考虑在[背景](http://stackoverflow.com/a/4530659/230513)中加载图像。 – trashgod 2013-02-10 19:24:54

回答

0

我想补充的ImageIconJLabel,然后添加到JLabelJDialog contentPane的后面是this.validate并在构造this.repaint

要进行调试,有时你需要实际的代码,而这些都只是基于假设

+0

为什么要验证()和重绘)'setVisible()'之前'?可悲的是,我没有看到'pack()'。 – trashgod 2013-02-10 19:22:53

+0

我认为,该代码存在。我刚刚提到了用于ImageIO.read()的步骤 – Horizon 2013-02-10 19:32:23

4

图像通常放在“资源”的源文件夹的建议,

enter image description here
然后作为访问字节流,

package com.foo; 

import java.io.IOException; 
import javax.imageio.ImageIO; 
import javax.swing.ImageIcon; 
import javax.swing.JDialog; 
import javax.swing.JLabel; 
import javax.swing.SwingUtilities; 

public class Demo 
{ 
    private static final String IMAGE_URL = "/resource/bar.png"; 

    public static void main(String[] args) 
    { 
     createAndShowGUI(); 
    } 

    private static void createAndShowGUI() 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      @Override 
      public void run() 
      { 
       try 
       { 
        JDialog dialog = new JDialog();  
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); 
        dialog.setTitle("Image Loading Demo"); 

        dialog.add(new JLabel(new ImageIcon(ImageIO.read(getClass().getResourceAsStream(IMAGE_URL))))); 

        dialog.pack(); 
        dialog.setLocationByPlatform(true); 
        dialog.setVisible(true); 
       } 
       catch (IOException e) 
       { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 
} 

产生摩根弗里曼。

enter image description here

+1

+1,但是ImageIcon可以直接使用由getResource()返回的URL。 – trashgod 2013-02-10 19:29:53

+1

@trashgod,+1但我想使用'getResourceAsStream' – mre 2013-02-10 19:52:35