JPanel不通过Timer重新绘制

时间:2015-02-09 02:37:14

标签: java swing jframe

所以我有这个班级,这是我的主要小组:

public class Frogger extends JPanel {

    private static final int WINDOW_WIDTH = 640;
    private static final int WINDOW_HEIGHT = 480;

    private static final Entity frog;
    private static final Entity car;

    static {
        frog = new Entity("sprites/frog.png", WINDOW_WIDTH / 2 - 75, WINDOW_HEIGHT - 190);
        car = new Entity("sprites/car.png", 0, WINDOW_HEIGHT / 2);
    }

    private static KeyListener genGameListener() {
        return new KeyListener() {
            @Override
            public void keyPressed(KeyEvent e) {}

            @Override
            public void keyReleased(KeyEvent e) {
                switch (e.getKeyCode()) {
                    case KeyEvent.VK_LEFT:
                        frog.move(-50, 0);
                        System.out.println("lol");
                        break;
                }
            }

            @Override
            public void keyTyped(KeyEvent e) {}
        };
    }

    @Override
    public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.WHITE);
        frog.draw(g2d);
        car.draw(g2d);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Frogger!");
        Frogger frogger = new Frogger();
        frogger.addKeyListener(genGameListener());
        frogger.setFocusable(true);
        frame.add(frogger);
        frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Timer timer = new Timer(100, (ActionEvent e) -> {
            car.move(50, WIDTH);
            frogger.repaint();
        });
    }
}

使用Entity类:

public class Entity {

    private BufferedImage sprite;

    private final AffineTransform at;

    private final int width;
    private final int height;

    private int x;
    private int y;

    public Entity(String imageFileName, int x, int y) {
        sprite = null;
        try {
            this.sprite = ImageIO.read(new File(imageFileName));
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
        width = sprite.getWidth();
        height = sprite.getHeight();
        this.x = x;
        this.y = y;
        at = new AffineTransform();
        at.translate(x, y);
    }

    public void draw(Graphics2D g) {
        g.drawImage(sprite, at, null);
    }

    public void rotate(int radians) {
        at.rotate(radians);
    }

    public void move(int dx, int dy) {
        x += dx;
        y += dy;
        at.translate(dx, dy);
    }
...

但是,我的关键操作不是更新精灵,而且汽车没有像计划定时那样在屏幕上移动。为什么框架没有被重新绘制?

1 个答案:

答案 0 :(得分:3)

您永远不会在Timer对象上调用start()