我试图创建一个浮动对话框,其中包含一个加载器gif图像和一些文本。我有以下课程:

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和Label。

我在此代码中做错了什么?

非常感谢。

最佳答案

图像通常放置在“资源”源文件夹中,



然后作为字节流进行访问,

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();
                }
            }
        });
    }
}


生产摩根·弗里曼(Morgan Freeman)。

09-10 06:41
查看更多