问题
First of all I'm new to Java and you'll probably be able to guess. Thanks in advance.
I'm currently writing a board game using Java for an assignment. There are human and computer player classes, and the GUI only in the human player class. In the human class I use a class called 'UI' extending JFrame where the user selects a piece.
At the moment this UI class waits for the enter button to be pressed then sets a 'done' variable to true. In the human player class I create this UI then wait in a while loop continuously checking this boolean before getting the X/Y position of the move.
while (!input.moveEntered());
move.setPosition(input.getX(), input.getY());
This only seems to work if the while loop is not empty. If I add a print statement in there it works fine. It seems like there is a much better way to go about this. I've looked into dialogs but I don't close the window every time a move is entered.
Thanks for reading.
回答1:
You should never be busy-waiting; in your case, I would show a modal JDialog. When the user has entered their input, the setVisible(true) method will end without busy-waiting.
Or maybe I misunderstood your problem and you only need to define an event listener in your main JFrame in order to handle user input. Have a look at http://www.tutorialspoint.com/swing/swing_event_listeners.htm
来源:https://stackoverflow.com/questions/36419330/waiting-for-a-jframe-and-then-retrieving-information-from-it