Thread.sleep()总是在sleep()语句执行之前暂停JFrame。 我有以下方法来暂停线程:
private void sleep(int milli) {
try {
Thread.sleep(milli);
} catch (InterruptedException ex) {
writeToConsoleError("Interrupted");
}
}
我在CARDNOMATCH案例中的以下switch-case语句中调用它:此方法位于扩展JFrame的类中。
public void handlePacket(Packet recieved) {
int cmd = recieved.getCommand();
int arg1 = -99;
int arg2 = -99;
switch (cmd) {
case CARDNOMATCH:
arg1 = recieved.getFirstArg();
arg2 = recieved.getSecondArg();
if(arg1 > 9) {
arg1 = 9;
}
if(arg2 > 9) {
arg2 = 9;
}
flipCard(choice1, arg1);
flipCard(choice2, arg2);
sleep(3000);
flipCard(choice1, 10);
flipCard(choice2, 10);
break;
case ENABLE_TURN:
this.isTurn = true;
break;
case DISABLE_TURN:
this.isTurn = false;
break;
}
}
请任何人,给我一些见解:(
答案 0 :(得分:3)
UI不会立即更新。
致电时
flipCard(choice1, arg1);
flipCard(choice2, arg2);
我假设flipCard
以某种方式更新了用户界面。您的预期行为是choice1
和choice2
卡将被翻转,等待3秒,然后再次翻转它们。但你得到的实际行为是,在3秒钟之后没有任何事情发生,3秒后卡片翻转两次。
您需要了解的是UI具有帧速率。当您拨打flipCard
时,该卡将不会翻到下一帧。在此帧与下一帧之间的时间内,Thread.sleep
被调用,因此包括帧在内的所有内容都会暂停3秒。这就是暂停3秒后UI更新的原因。
我建议您使用javax.swing.Timer
或javax.swing.SwingWorker
。有关详细信息,请参阅here或here。