Waiting for a JFrame and then retrieving information from it

会有一股神秘感。 提交于 2019-12-12 01:36:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!