Waiting until the player clicks a chess piece in Java-Collection of common programming errors
What is the proper way to implement the following code? I want to get the takeTurn() method to wait for the player to click on a button on the grid corresponding to the piece he wants to select. (Button
objects have instance variables int col, row
and extend JButton
.)
int selectedCol, selectedRow;
void takeTurn() {
System.out.print(name + "'s turn. ");
// Get player to select a piece
selectedCol = -1;
selectedRow = -1;
while (selectedCol == -1 && selectedRow == -1) {
try {
wait(500);
} catch (InterruptedException e) {
}
}
System.out.println(selectedCol + " " + selectedRow);
}
@Override
public void actionPerformed(ActionEvent e) {
Button b = (Button)e.getSource();
selectedCol = b.col;
selectedRow = b.row;
}
Running gives Exception in thread "main" java.lang.IllegalMonitorStateException
.