Exception : adding a window to a container. How to solve it?

一个人想着一个人 提交于 2019-11-30 09:21:04

问题


I have a JDialog class named Preferences. This class creates a constructor like:

class Preferences extends javax.swing.JDialog {
          Preferences(java.awt.Frame parent,modal)  {
                      super(parent,modal);
                      //......
          }
}

In my program I want this preferences dialog to open up as I click a button from a JFrame form. After I registered the action listener on the button, I wrote the code inside as:

Frame fr = new Frame();
Preferences p = new Preferences(fr,false);
fr.add(p);
fr.setVisible(true);

When I run this code I get the following exception (as I click the button):

Exception in thread "AWT-EventQueue-0" 
    java.lang.IllegalArgumentException: adding a window to a container

What does this mean and how can I solve it?


回答1:


What does this mean..

One top level container (dialog) cannot be added to another (frame).

..and how can i solve this ?

Just call setVisible(true) on the Preferences dialog, rather than adding it.




回答2:


You don't add the JDialog to the JFrame, that makes no sense whatsoever since the add(...) method is for adding components to be displayed in the container, not by the container. You display the JDialog from the JFrame's JButton's ActionListener. You also shouldn't be mixing AWT (Frame) components and Swing components together for no good reason.

Your question suggests that you would benefit greatly by going through the Swing tutorials.




回答3:


JDialog and JFrame are top-level container. I suggest that you should have to use JFrame, JInternalFrame and JDesktopPane.



来源:https://stackoverflow.com/questions/8410616/exception-adding-a-window-to-a-container-how-to-solve-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!