0

有人可以告诉我有什么问题吗?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)
4

2 回答 2

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异常的原因。

于 2013-09-12T09:10:56.170 回答
2

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

于 2013-09-12T08:39:18.887 回答