gpt4 book ai didi

java - 线程和 GUI 显示

转载 作者:行者123 更新时间:2023-12-01 22:20:14 24 4
gpt4 key购买 nike

    public void actionPerformed(ActionEvent event) {        
for(int i=0;i<9;i++) {
if(event.getSource()==button[i]) {
//button[i].setText(i+"");
if(isFirstPlayer) {
button[i].setText(p1.symbol+"");
display.setText(p2.name + "'s turn");
isFirstPlayer=false;
} else {
button[i].setText(p2.symbol+"");
display.setText(p1.name + "'s turn");
isFirstPlayer=true;
}
int result = getGameStatus();
if(result!=NOT_FINISHED) {
if (result ==PLAYER1_WON) {
display.setText(p1.name + " won!");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int z=0;z<9;z++) {
button[z].setText("");
}
display.setText(p1.name+"'s turn");
} else if (result == PLAYER2_WON) {
display.setText(p2.name + " won!");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int z=0;z<9;z++) {
button[z].setText("");
}
display.setText(p2.name+"'s turn");
} else {
display.setText("Draw!");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int z=0;z<9;z++) {
button[z].setText("");
}
display.setText(p1.name+"'s turn");
}
}
}
}
}

当我执行此操作时,线程会立即执行,因为我想先显示文本,然后我希望线程完成其工作...为什么首先调用线程以及如何纠正它?

最佳答案

Thread.sleep() 完成的 sleep 是在事件调度线程上完成的,这将锁定 GUI。

因此,如果您需要等待特定的时间,请不要在事件调度线程中 hibernate 。相反,请使用 timer

 int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
};
new Timer(delay, taskPerformer).start();

关于java - 线程和 GUI 显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30005062/

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