1

由于某种原因,paintComponent 没有被调用。如果线程没有产生,它将运行一次。为什么线程阻止它运行?

package com.example.cellcitygame;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

/**
 * Manages memory, entities, map, objects, etc.
 * 
 * @author John Smith
 */

public class Scene extends JPanel {
    public ArrayList<Entity> entities = new ArrayList<>();

    Image background;
    Image good;
    Image bad;
    Image digested;
    Image protein1;
    Image protein2;
    Image protein3;
    Image protein4;

    public Scene() {
        background = new ImageIcon(this.getClass().getResource("BG.png"))
                .getImage();
        good = new ImageIcon(this.getClass().getResource("Good.png"))
                .getImage();
        bad = new ImageIcon(this.getClass().getResource("Bad.png")).getImage();
        digested = new ImageIcon(this.getClass().getResource("Digested.png"))
                .getImage();
        protein1 = new ImageIcon(this.getClass().getResource("Protein1.png"))
                .getImage();
        protein2 = new ImageIcon(this.getClass().getResource("Protein2.png"))
                .getImage();
        protein4 = new ImageIcon(this.getClass().getResource("Protein4.png"))
                .getImage();
        protein3 = new ImageIcon(this.getClass().getResource("Protein3.png"))
                .getImage();

        Entity test = new Entity();
        test.targetX = 500;
        test.targetY = 300;
        test.x = 100;
        test.y = 100;
        entities.add(test);

        new UpdateThread().start();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        for (Entity entity : entities) {
            entity.draw(g);
        }

        Toolkit.getDefaultToolkit().sync();
        g.dispose();
    }

    class UpdateThread extends Thread {
        public void run() {
            while (true) {
                for (Entity entity : entities) {
                    entity.update();
                }

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                repaint();
            }
        }
    }
}

我想知道这是否与更新循环太快有关?

TIA

4

0 回答 0