How to change the image icon on a Java dialog (JDialog)

By Alvin J. Alexander, devdaily.com

We were just wondering how to change the icon image of a JDialog. Changing the 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 for me is usually a JFrame. So in the code sample below I'm showing two different ways to do this.

package com.devdaily.jdialogtest;

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

public class Foo {

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

}

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.


devdaily logo