0

I want to change extend Canvas to JFrame. But why does my program not run? Command prompt reports:

Exception in thread "main" java.langIllegalArgumentException: 
  adding a window to a container 
  at java.awt.Container.chekNotAWindow(Container.java:483)" and so many more  

Here is my code:

  class Layar extends Canvas implements Runnable,KeyListener
\\ init
    Layar()
    {
        super();
        try{
//adding a picture
            }
        catch(Exception e){}

    new Thread(this).start();
    addKeyListener(this);
    }
    public void update(Graphics g)
    {
        paint(g);
    }
    public void paint(Graphics g)
    {
        g.drawImage(img,x_back,y_back+200,null);//background

//key listener

    public void run()
    {
        //try catch
}


public class stage2
{
    public static void main(String[] args)
    {


        JFrame window = new JFrame("aaaa");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setLocation(50,50);
        window.setSize(700,700);
        window.setResizable(false);
        window.add(new Layar());
        window.setVisible(true);
    }
}
4

1 回答 1

3

本质上,一个窗口(或本例中的框架)不能添加到另一个窗口。

而不是使用

JFrame window = new JFrame("aaaa");

利用

Layar window = new Layar();

一旦您将 更改为Layar从 扩展JFrame

话说回来。就个人而言,您最好简单地扩展JPanel并继续添加Layar到您创建的框架。如果您尝试从顶级容器扩展,您将从自定义绘画中获得更好的性能。

您可能还想看看Custom Painting,因为您应该覆盖paintComponentSwing 组件而不是paint

于 2013-06-17T12:22:27.750 回答