java游戏循环,Java游戏循环(绘画)冻结了我的窗口

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();

}

});

}

}

}

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");

}

}

I'm painting using paintComponent()

public void paintComponent(Graphics g) {

System.out.println("paint");

...

}

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.)

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.)

Thanks.

解决方案

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();

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值