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

戏子无情 提交于 2019-12-02 10:53:29

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.

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

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