gpt4 book ai didi

java - 为什么 Thread.sleep() 在 Action Performed 中不起作用?

转载 作者:行者123 更新时间:2023-12-02 00:07:05 27 4
gpt4 key购买 nike

public void actionPerformed(ActionEvent e) {
String sp1="Player 1's turn. ";
String sp2="Player 2's turn. ";
System.out.println("Mouse entered for rating " + index); //helps me track the cards
ori=new ImageIcon(getClass().getResource(index+1+".png")); //set the image to the card

ori.setDescription("ori"); //It's weird that I cannot directly flip the card, so I used this method to flip the cards.
tail.setDescription("tail");//http://stackoverflow.com/questions/13557561/the-method-about-imageicons-does-not-work


if (((ImageIcon) bt[index].getIcon()).getDescription()=="ori")
bt[index].setIcon(tail);
else
bt[index].setIcon(ori);

count++;

System.out.printf("Action Performed %d times \n",count);
if(count==1){ //if the card is clicked for once, the card should not flip and the index is stored in record.
record=index;
countS++;

}
String turnS=Integer.toString(countS);//parse the int and printout the turn
// text3.setText(sp1+"This is turn "+turnS);
if(count==2){
int match1=record/4; //Since every four cards have the same rank, I used this to get the rank very easily
int match2=index/4;
if(match1==match2&&record!=index){ //compare the two cards clicked
p1++;
score1=Integer.toString(p1);
text1.setText("Player 1: "+score1); //display the score
text3.setText(sp2+"This is turn "+turnS);
bt[index].setEnabled(false);//remove the cards that match
bt[record].setEnabled(false);
}
if(record==index){
text3.setText(sp2+"This is turn "+turnS);//designed for the situation that the user clicks the same card
}
if(match1!=match2){//designed for the situation that the two cards do not match
//time.schedule(taskFlip1,500);//delay the flip so that the user can see the cards
//time.schedule(taskFlip2,500);


try{ **//This part is problematic!**

Thread.currentThread().sleep(4000);
flip(index);
flip(record);


}
catch(Exception ie){

}
}
text3.setText(sp2+"This is turn "+turnS);


}

当我单击按钮时,按钮应该更改 ImageIcon。不 sleep 也能正常工作。但是在我添加 sleep 之后,当我单击按钮时,程序暂停而不改变ImageIcon!你能告诉我为什么吗?谢谢!

最佳答案

actionPerformed() 方法在事件调度线程中运行。重绘系统也是如此。如果你 sleep ,你就会推迟绘画和其他一切。你永远不应该在这个线程中 sleep 。如果您想要延迟绘制,请使用 SwingWorkerjavax.swing.Timer 启动延迟任务。

关于java - 为什么 Thread.sleep() 在 Action Performed 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13615261/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com