在一定时间后打开卡 [英] Open card after certain time

查看:176
本文介绍了在一定时间后打开卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为一个大学项目编程一个二十一点(单线程),经销商是计算机(例如没有玩家动作)...

i'm programming a blackjack (single thread) for a university project and the dealer is the computer (e.g. no player action)...

我如何在Java中编程这样:

Does someone know how can I program in Java something like this:

while (dealerpoints < 17)
    open card and repaint frame
    wait 1 sec (to run again the condition test for while)

我不想一下所有的经销商卡...

THe thing is, I don't want all dealer cards painted at once...

提前感谢,
Gabriel Sotero

Thanks in advance, Gabriel Sotero

UPDATE:这是我的代码(不工作)

UPDATE: this is my code (that doesn't work)

        while (Dealer.getInstance().dealerPoints < 17){

            Dealer.getInstance().openCard();
            try {
                Thread.sleep(100);
            }
            catch (InterruptedException e){ }
        }

openCard声明:

openCard declaration:

    private void openCard(){

        Card temp;

        temp = Deck.getInstance().myPop();
        Dealer.getInstance().cards.add(temp);
        Dealer.getInstance().dealerPoints += temp.getValue(); 
        MainPanel.getInstance().updateDealerLabel(Dealer.getInstance().dealerPoints);
        MainPanel.getInstance().repaint();

    }


推荐答案

阻止事件分派线程,因为它负责(除其他事项外)处理重绘请求。所以所有的时间,你在等待,UI不开始更新。这包括使用循环和 Thread#sleep

You can't block the Event Dispatching Thread as it is responsible for (amongst other things) processing re-paint requests. So all the time you're waiting, the UI is not begin updated. This includes using loops and Thread#sleep.

一个解决方案是使用 SwingWorker ,但它不可靠

One solution is to use a SwingWorker, but, it's unreliable in terms of when it will call an update back to the UI.

另一个解决方案是使用 javax.swing.Timer 这将触发呼叫

The other solution would be to use a javax.swing.Timer which will trigger a call back every n periods and is executed within the Event Dispatching Thread...

像<...>

Timer dealerTimer= new Timer(1000, new ActionListener() {
    public void actionListener(ActionEvent evt) {
        if (Dealer.getInstance().dealerPoints < 17) {
            Dealer.getInstance().openCard();
        } else {
            ((Timer)evt.getSource()).stop();
        }
    }
});
dealerTimer.setRepeats(true);
dealerTimer.start();

我要做的是声明 dealerTimer 作为类字段。当需要时,我只需调用 dealerTimer.restart()即可重新启动计时器。您可能还需要检查 dealerTimer.isRunning(),以确保计时器尚未运行;)

What I would do, is declare dealerTimer as a class field. When required, I would simply call dealerTimer.restart() to get the timer to restart. You might also want to check dealerTimer.isRunning() to make sure that the timer isn't already running ;)

您可能希望阅读 Swing中的并发有关更多信息

You might like to have a read through Concurrency in Swing for some more information

这篇关于在一定时间后打开卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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