Chr*_*on4 1 java swing multithreading awt actionlistener
我有一个简单的、大小不一的井字棋应用程序,它在不同的机器上工作方式不同。在我的笔记本电脑上,它像我想要的那样工作,而在我的台式机上,它卡在ButtonListener
实现ActionListener
. 我很确定这是因为我使用while
循环等待执行操作的方式。这是有问题的代码片段。
public void playOneTurn(int player) {
waiting = true;
while (waiting) {
// Do nothing, touchEvent will change waiting.
}
}
Run Code Online (Sandbox Code Playgroud)
我的意思是让这个方法简单地等待一个有效的点被选择并waiting
在ButtonListener
:
class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("TOUCHEVENT");
for (i = 0; i < size; i++)
for (j = 0; j < size; j++)
if (e.getSource() == cells[i][j]) {
if (model[i][j] == 'e') {
cells[i][j].setText("");
currentSpot[0] = i;
currentSpot[1] = j;
if (count % 2 == 0) {
cells[i][j].setBackground(Color.GREEN);
cells[i][j].setIcon(X_MARK);
model[i][j] = 'x';
count++;
waiting = false;
} else {
cells[i][j].setBackground(Color.CYAN);
cells[i][j].setIcon(O_MARK);
model[i][j] = 'o';
count++;
waiting = false;
}
} else {
System.out.println("Hey, you can't move there silly!");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我对线程一无所知,但我相信它ButtonListener
正在启动一个线程,并且由于我等待它的方式,使用while
循环,线程永远不会停止,让我的其余代码在某些机器上运行。
我在使用 while 循环等待事件翻转布尔值时是否有错误,如果是这样,我将如何正确等待它?
归档时间: |
|
查看次数: |
3678 次 |
最近记录: |