问题
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();
}
回答1:
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.Timer which will trigger a call back every n periods and is executed within the Event Dispatching Thread...
Something like...
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();
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 ;)
You might like to have a read through Concurrency in Swing for some more information
回答2:
You could use: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html#sleep(long). Put it in a try-except block.
// To wait 1 second:
try {
Thread.sleep(1000);
} catch (Exception e) {}
回答3:
go to sleep for a bit
try {
Thread.sleep(1000);
}catch (InterruptedException e){
LOG.warning("unexpected interruption while sleeping");
}
来源:https://stackoverflow.com/questions/13617871/open-card-after-certain-time