java.lang.IllegalArgumentException: adding a window to a container

后端 未结 2 502
我在风中等你
我在风中等你 2021-01-27 14:13

I get \'java.lang.IllegalArgumentException: adding a window to a container\' when I call frame.add(this). What am I doing wrong, and how do I fix the error. Thanks in advance.

相关标签:
2条回答
  • 2021-01-27 14:33

    mainclass extends from JFrame. You can not a window to a container, that's just the way it is.

    Try making mainclass extend from something like JPanel instead.

    I'm also concerned about new ImageIcon("res/icon.png"). This looks very much like the icon.png is an embedded resource rather than a file on the file system. You may find you need to use new ImageIcon(getClass().getResource("/res/icon.png")) instead, but I don't have enough context to 100% sure

    0 讨论(0)
  • 2021-01-27 14:44

    The simple answer is that you can't do this. Your question would benefit from describing why you would want to do this - what end result are you trying to achieve?

    If you're trying to add another container then you should use JPanels. If you are trying to create an MDI-like app, then you should look at JInternalFrames. If you want a popup frame, you need JDialogs.

    For a little more information, JFrames are designed to be top-level containers - they contain a JRootPane as its only child. When you want to add something to a frame you are in effect adding to the frame's root pane, referred to as the content pane. The correct way is to call frame.getContentPane().add().

    This was a constant source of frustration because a lot of developers instinctively wanted to call frame.add() which is how practically all the other Swing components work. Therefore as a convenience frame.add() has been overridden to call frame.getContentPane().add().

    So if you think about what's happen in your example now, you are trying to add a JFrame to a frame's root content pane. Understandably root panes cannot have other top-level containers as child elements, eg JFrames as they possess their own root pane.

    0 讨论(0)
提交回复
热议问题