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

后端 未结 2 526
我在风中等你
我在风中等你 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: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.

提交回复
热议问题