Java游戏循环(绘画)冻结了我的窗口 [英] Java game loop (painting) freezes my window

查看:88
本文介绍了Java游戏循环(绘画)冻结了我的窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用cardLayout更改视图(此类具有 JFrame 变量)。当用户点击新游戏按钮时会发生这种情况:

I'm changing "views" with cardLayout (this class has a JFrame variable). When a user clicks a new game button this happens:

public class Views extends JFrame implements ActionListener {

    private JFrame frame;
    private CardLayout cl;
    private JPanel cards;
    private Game game;

    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        if (command.equals("New game")) {
            cl.show(cards, "Game");

            game.init();
            this.revalidate();
            this.repaint();

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    game.loop();
                }
            });
        }
    }
}

游戏的循环方法和标题class:

Game's loop method and heading of class:

public class Game extends JPanel implements KeyListener {
    public void loop() {
        while (player.isAlive()) {
            try {
                this.update();
                this.repaint();
                // first class JFrame variable
                jframee.getFrame().repaint();
                // first class JFrame variable
                jframee.getFrame().revalidate();
                Thread.sleep(17);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public void update() {
        System.out.println("updated");
    }
}

我正在使用绘画paintComponent()

public void paintComponent(Graphics g) {
    System.out.println("paint");
    ...
}

实际上它并没有画任何东西。当我不调用 loop()方法(因此它只绘制一次)所有图像都被正确绘制。但是当我调用 loop()方法时,窗口中什么也没发生。 (即使 JFrame 上的关闭按钮也不起作用。)

Actually it's not painting anything. When I do not call loop() method (so it paints it just once) all images are painted correctly. But when I call loop() method, just nothing is happening in the window. (Even close button on JFrame doesn't work.)

如何修复? (当我在游戏类中创建 JFrame 时,一切正常,但现在我想要更多视图,所以我需要 JFrame 在其他课程中。)

How to fix that? (When I was creating JFrame inside game class everything worked fine, but now I want to have more views so I need JFrame in other class.)

谢谢。

推荐答案

什么更新吗?您可能不应该在EDT上调用 game.loop()。你正在EDT上运行一个循环,你的重绘不会被调用,因为重绘在EDT上排队一个事件,它似乎很忙。尝试将 game.loop()移动到另一个线程

What does update do? You probably shouldnt call game.loop() on the EDT. You are running a loop on EDT, your repaint wont ever be invoked since repaint queues an event on EDT and it seems kind busy. Try moving game.loop() to another thread

new Thread(new Runnable() {
    @override
    public void run() {
        game.loop();
    }
}).start();

这样你就不会阻止EDT,而重绘仍然在EDT上执行。

This way you wont block the EDT while the repaint still gets to be executed on the EDT.

这篇关于Java游戏循环(绘画)冻结了我的窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆