PaintComponent在列表中找不到元素

时间:2019-12-01 12:03:29

标签: java paintcomponent

我的paintComponent在实体中找不到元素,因此不会绘制它。当我在paintComponent中打印实体时,它只是给我一个空的List。

我也很难理解paintComponent及其工作原理。

当我在构造函数中打印出实体时: println(this.entities)初始化后会给出一个包含两个元素的列表 [snake.Snake@27bb80c2, snake.Apple@157d2026]

package snake;

import java.awt.Color;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Graphics;

public class GameWindow extends JPanel implements KeyListener {

    JLabel label;
    int blockSize = 20;
    Tuple dim;
    List<Entity>entities;

    public GameWindow(String s, Tuple dim, List<Entity>entities){
        this.entities = entities;
        JFrame frame = new JFrame(s);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(this);
        frame.setSize(dim.x*blockSize, dim.y*blockSize);
        frame.addKeyListener(this)
        ;
        frame.setVisible(true);


        this.dim = dim;
    }

    @Override
    public void paintComponent(Graphics g) {
        g.setColor(Color.black);
        g.fillRect(0, 0, dim.x*blockSize, blockSize* dim.y);

        for (int i = 0; i < entities.size(); i++) {
            if (entities.get(i) instanceof Snake){
                g.setColor(entities.get(i).headColor);
                if (entities.get(i).body.size() != 0) {
                    g.fillRect(entities.get(i).body.get(0).x, entities.get(i).body.get(0).y, blockSize, blockSize);
                }
                g.setColor(entities.get(i).tailColor);
                for (Tuple p : entities.get(i).body) {
                    g.fillRect(p.x, p.y, blockSize, blockSize);
                }
            }
            else if (entities.get(i) instanceof Apple){
                g.setColor(entities.get(i).color);
                // g.fillRect(e.pos.x, e.pos.y, blockSize, blockSize);
            }
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
        // Nothing
    }

    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println("Key Pressed");
        for (Entity s: entities){
            s.keyInput(e.getKeyCode());
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // Nothing 
    }
}

0 个答案:

没有答案