JDialog icon - how to change the icon on a Java dialog (JDialog)

A couple of us were just working on a Java application that uses a JDialog, and were wondering how to change the icon image of a JDialog (a Java dialog).

Changing the JDialog icon image doesn't seem to be too hard, though it's not quite as simple as you might think. It turns out that the JDialog inherits the icon image from it's parent, which in my case is a JFrame. So in the code sample below I'm showing two different ways to do this.

JDialog example - changing the Java dialog icon

package com.devdaily.jdialogicon;

import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;

public class JDialogIconExample {

  public static void main(String[] args)
  {
    Image img = new ImageIcon(Foo.class.getResource("add.png")).getImage();
    JFrame f = new JFrame("The Frame");
    // option 1: it works if i set an image on the parent frame here
    //f.setIconImage(img);
    JDialog j = new JDialog(f);
    // option 2: it works if i set an image on the parent frame this way
    ((java.awt.Frame)j.getOwner()).setIconImage(img);
    j.setModal(true);
    j.setVisible(true);
  }

}

JDialog icon example - discussion

Option #1 shows a very straightforward way of doing this. Just set the image icon on the parent JFrame, and then create your JDialog. Option #2 shows a way of faking things out a little bit. In this case you get the owner of the JDialog, then set the icon image on that owner.

If you don't want any image at all on your dialog a good way of accomplishing this is to use the JOptionPane class and its dialog constructors.

It's also important to note that I should have done some of this work on the Event Dispatch Thread (EDT) by using SwingUtilities.invokeLater, but I skipped that step to keep this simple. See this JFrame example for an example of how to create a JFrame on the EDT.