-2

I am trying to assign a favicon to a JDialog. This code works, but the image ends up hardcoded.

ImageIcon favImageIcon = new ImageIcon("../images/default.gif");
Image favIconImage=  favImageIcon.getImage();
dialog.setIconImage(favIconImage);

Parent frame already has a favicon. How can I set JDialog to use favicon of it's parent? I tried dialog.setIconImage(super); but this is clearly incorrect.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
sixtytrees
  • 1,156
  • 1
  • 10
  • 25

2 Answers2

3

How can I set JDialog to use favicon of it's parent?

Use the parent as the parent of the dialog. Vis.

enter image description here

import java.awt.image.BufferedImage;
import javax.swing.*;

public class DialogIconByParent {

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(
                            UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                BufferedImage bi = 
                        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);

                JFrame f = new JFrame(new DialogIconByParent()
                        .getClass().getSimpleName());
                f.setIconImage(bi);
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(new JLabel(new ImageIcon(
                        new BufferedImage(400, 200, BufferedImage.TYPE_INT_RGB))));
                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);

                // This hints to use the frame's icon, among other things.
                JDialog d = new JDialog(f); 
                d.add(new JLabel(new ImageIcon(
                        new BufferedImage(250, 100, BufferedImage.TYPE_INT_RGB))));
                d.pack();
                d.setLocationRelativeTo(f);
                d.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
0

you can use an image file from resources in jar file.

 URL url =getClass().getResource("/Media/something.png");
 ImageIcon imageIcon = new ImageIcon(url);

and this wont be hard coded!

RayanFar
  • 539
  • 11
  • 28