线程“main”中的异常java.lang.IllegalArgumentException:向容器添加窗口

时间:2013-09-12 08:37:18

标签: java swing

有人可以告诉我这是什么问题吗? Camera类是扩展Jpanel

代码:

    public class Main extends JFrame {
       public static Image image;
    //sort the cameras by their heights.
        public static void main(String [] args){
            image = new Image(400,400,"test");
            Camera c=new Camera(100, 100, (Math.PI)/4, 0, 200,200,Math.PI,Color.MAGENTA);
            image.addCamera(c);
            JFrame f = new JFrame();
            int width= image.getWidth();
            int length = image.getLength();
            f.setSize(width, length);
            f.add(new Main());
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       //Sets the title of the frame
            f.setTitle(image.getName());
            f.setVisible(true);

        }

    public void paint(Graphics g) {
        System.out.println("in the paint");
        Vector<Camera> cameras = image.getCameras();
        for(int i=0;i<cameras.size();i++){
            cameras.get(i).paintComponent(g);
         }
    `enter code here`}

在类Camera中有paintCompoment函数, 但结果是:

 Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a         container
    at java.awt.Container.checkNotAWindow(Container.java:483)
    at java.awt.Container.addImpl(Container.java:1084)
    at java.awt.Container.add(Container.java:998)
    at javax.swing.JFrame.addImpl(JFrame.java:562)
    at java.awt.Container.add(Container.java:410)
    at CameraPack.Main.main(Main.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

2 个答案:

答案 0 :(得分:2)

您正尝试将JFrame(您的主类)添加到另一个JFrame(f)。这不会飞,因为它们都是Windows

答案 1 :(得分:2)

JFrame的add()函数接受一个Component参数,该参数不能是Window的一个实例。

所以在你的add()方法之间的某个地方调用checkNotAWindow(component);。在你的情况下,组件是另一个JFrame。

/**
 * Checks that the component is not a Window instance.
 */
private void checkNotAWindow(Component comp){
    if (comp instanceof Window) {
        throw new IllegalArgumentException("adding a window to a container");
    }
}

现在JFrame extends FrameFrame extends Window使您的组件(JFrame)窗口实例成为adding a window to a container例外的原因。