为什么会出现这个错误?线程“main”中的异常java.lang.IllegalArgumentException:向容器添加窗口

时间:2021-08-01 19:56:36

标签: java window

我似乎无法打开窗户,有人能帮我理解为什么会这样吗?

这是我目前的代码:

在“new GameGrame()”上,它还说“新实例被忽略”,我不明白为什么,因为我不会一遍又一遍地回忆一个变量(如果我创建了一个GameFrame)。我只想为它创建一个新对象,以便显示窗口。

package snake;

public class Snake{

    public static void main(String[] args){
        new GameFrame();
    }
    
}

和:

package snake;

import javax.swing.JFrame;
public class GameFrame extends JFrame{
    
    GameFrame(){
        
        this.add(new GamePanel());
        this.setTitle("Snake");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.pack();
        this.setVisible(true);
        this.setLocationRelativeTo(null);
    }
}

和:

package snake;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class GamePanel extends JFrame implements ActionListener {
    
    static final int SCREEN_WIDTH = 600;
    static final int SCREEN_HEIGHT = 600;
    static final int UNIT_SIZE = 25;
    static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/UNIT_SIZE;
    static final int DELAY = 75;
    final int x[] = new int[GAME_UNITS]; //GAME_UNITS = size since snake won't be bigger than game space
    final int y[] = new int[GAME_UNITS];
    int bodyParts = 6;
    int applesEaten = 0;
    int appleX;
    int appleY;
    //direction
    char direction = 'R'; //start toward right
    boolean running = false;
    Timer timer;
    Random random;
    
    GamePanel(){
        random = new Random();
        this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
        this.setBackground(Color.BLACK);
        this.setFocusable(true);
        this.addKeyListener(new MyKeyAdapter());
        startGame();
    }
    public void startGame(){
        newApple();
        running = true;
        timer = new Timer(DELAY, this);
        timer.start();
    }
    public void paintComponent(Graphics g){
        super.paintComponents(g);
        draw(g);
    }
    public void draw(Graphics g){
        
        for (int i=0; i < SCREEN_HEIGHT/UNIT_SIZE; i++){
            g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT);
        }
        
    }
  

和:

public class MyKeyAdapter extends KeyAdapter{
        
        @Override
        public void keyPressed(KeyEvent e){
            
        }
    }

0 个答案:

没有答案