简体   繁体   English

如何从其JPanel内容更改JDialog图标?

[英]How to change JDialog icon from its JPanel content?

I've a JDialog and JPanel 我有一个JDialogJPanel


...
MyPanel panel = new MyPanel();
JDialog dialog = new JDialog();
dialog.add(panel);
dialog.show();
...

public class MyPanel extends javax.swing.JPanel {
    ....
}

How can I change the icon of dialog from MyPanel class when it is opened? 打开MyPanel类后,如何更改对话框的图标?

My code: 我的代码:

...    
initComponents();

1. ((JFrame)((JDialog)this.getParent()).getOwner()).setIconImage(img);

2. Window win = SwingUtilities.getWindowAncestor(this);
   win.setIcon(img);

Both are returning NullPointerException 两者都返回NullPointerException

It returns null because you're calling these methods from withing the constructor of the panel. 它返回null,因为您是从面板的构造函数中调用这些方法的。 And when the panel is constructed, it's not added to the dialog yet. 并且在构造面板时,尚未将其添加到对话框中。

Either set the icon from the outside: 可以从外部设置图标:

MyPanel panel = new MyPanel();
JDialog dialog = new JDialog();
dialog.add(panel);
dialog.setIconImage(...);
dialog.show();

or add an AncestorListener to the panel to be notigied when it's being made visible, and set the icon from the listener method. 或将AncestorListener添加到要使其可见的面板上,然后通过listener方法设置图标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM