i’m programming a blackjack (single thread) for a university project and the dealer is the computer (e.g. no player action)…
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…
Thanks in advance,
Gabriel Sotero
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 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();
}
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.One solution is to use a
SwingWorker, but, it’s unreliable in terms of when it will call an update back to the UI.The other solution would be to use a
javax.swing.Timerwhich will trigger a call back every n periods and is executed within the Event Dispatching Thread…Something like…
What I would do, is declare
dealerTimeras a class field. When required, I would simply calldealerTimer.restart()to get the timer to restart. You might also want to checkdealerTimer.isRunning()to make sure that the timer isn’t already running 😉You might like to have a read through Concurrency in Swing for some more information