1

I tried to create a floating dialog box which contains a loader gif image and some text. I have got the following class:

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

However, when I call:

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

An empty dialog is shown. The ImageIcon and the Label is not shown in the dialog box.

What did I do wrong in this code?

Many thanks.

mre
  • 43,520
  • 33
  • 120
  • 170
Kevin
  • 5,972
  • 17
  • 63
  • 87

2 Answers2

4

Images are usually placed into a "resource" Source Folder,

enter image description here
and then accessed as a byte stream,

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

to produce Morgan Freeman.

enter image description here

mre
  • 43,520
  • 33
  • 120
  • 170
0

I would add the ImageIcon to a JLabel and then add JLabel to JDialog contentPane followed by a this.validate and this.repaint in the constructor.

To debug, sometimes you need actual code without which these are just suggestions based on assumptions

Horizon
  • 548
  • 3
  • 7