如何使用父级的 JDialog 图标?

How to use parent's favicon for JDialog?

我正在尝试将网站图标分配给 JDialog。此代码有效,但图像最终被硬编码。

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

父框架已有一个图标。如何设置 JDialog 以使用其父级的图标?我试过 dialog.setIconImage(super); 但这显然不正确。

您可以在 jar 文件中使用资源中的图像文件。

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

这不会被硬编码!

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

使用父级作为对话框的父级。可见

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