[英]Problems with my Thread.sleep()
我正在创建一个简单的视频扑克程序,现在我正在研究用户指定他想要持有的牌后执行的操作,并在抽牌后用新牌替换丢弃的牌。 我有一个动作,我想在所有更换之间延迟一张一张地更换卡片,但是使用下面的代码,它将休眠 500 毫秒乘以我必须更换的卡片数量,然后全部更换立即更换卡片,而不是按照我的意愿一次更换一张。 任何帮助是极大的赞赏!
Action drawAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
int deckPos = 5;
if((holdValFirst.getText()).equals("HELD")){}
else{
holdFirst.setIcon(new ImageIcon(((deck.getDeck())[deckPos]).getCardName()+".gif"));
deckPos++;
try
{
Thread.sleep(500);
}catch (InterruptedException ie){
System.out.println(ie.getMessage());
}
}
if((holdValSecond.getText()).equals("HELD")){}
else{
holdSecond.setIcon(new ImageIcon(((deck.getDeck())[deckPos]).getCardName()+".gif"));
deckPos++;
try
{
Thread.sleep(500);
}catch (InterruptedException ie){
System.out.println(ie.getMessage());
}
}
if((holdValThird.getText()).equals("HELD")){}
else{
holdThird.setIcon(new ImageIcon(((deck.getDeck())[deckPos]).getCardName()+".gif"));
deckPos++;
try
{
Thread.sleep(500);
}catch (InterruptedException ie){
System.out.println(ie.getMessage());
}
}
if((holdValFourth.getText()).equals("HELD")){}
else{
holdFourth.setIcon(new ImageIcon(((deck.getDeck())[deckPos]).getCardName()+".gif"));
deckPos++;
try
{
Thread.sleep(500);
}catch (InterruptedException ie){
System.out.println(ie.getMessage());
}
}
if((holdValFifth.getText()).equals("HELD")){}
else{
holdFifth.setIcon(new ImageIcon(((deck.getDeck())[deckPos]).getCardName()+".gif"));
deckPos++;
}
}
};
当您在事件调度线程 (EDT) 中休眠时,GUI 被冻结。 每个长时间运行的任务都应该在 EDT 之外完成,所有 swing 操作都应该在 EDT 中完成。
您应该使用SwingWorker
在另一个线程中休眠,并每 500 毫秒发布一些进度。 或者您可以使用javax.swing.Timer
每 500 毫秒触发一次事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.