我是靠谱客的博主 贪玩冬瓜,最近开发中收集的这篇文章主要介绍java怎么往窗口中添加容器,java.lang.IllegalArgumentException:向容器添加窗口,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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.

public class mainclass extends JFrame{

private static final long serialVersionUID = 1L;

private int width = 400;

private int height = 400;

public static JFrame frame;

public static void main(String args[]) {

frame = new JFrame();

mainclass mainclass = new mainclass();

mainclass.createFrame();

}

public void createFrame() {

frame.setSize(new Dimension(width, height));

frame.setDefaultCloseOperation(EXIT_ON_CLOSE);

frame.add(this); // this is where the error occurs

frame.setResizable(false);

frame.setLocationRelativeTo(null);

frame.setVisible(true);

frame.setIconImage(new ImageIcon("res/icon.png").getImage());

}

}

Stacktrace:

Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container

at java.awt.Container.checkNotAWindow(Unknown Source)

at java.awt.Container.addImpl(Unknown Source)

at java.awt.Container.add(Unknown Source)

at javax.swing.JFrame.addImpl(Unknown Source)

at java.awt.Container.add(Unknown Source)

at test.mainclass.createFrame(mainclass.java:27)

at test.mainclass.main(mainclass.java:21)

解决方案

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.

最后

以上就是贪玩冬瓜为你收集整理的java怎么往窗口中添加容器,java.lang.IllegalArgumentException:向容器添加窗口的全部内容,希望文章能够帮你解决java怎么往窗口中添加容器,java.lang.IllegalArgumentException:向容器添加窗口所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(42)

评论列表共有 0 条评论

立即
投稿
返回
顶部