I am writing a small game, with one JFrame that holds the main game, and another JFrame that displays the score. the problem is, when I am done constructing them, the score JFrame always ends up focused! I have tried calling scoreDisplay.toFront(), scoreDisplay.requestFocus(), and even:
display.setState(JFrame.ICONIZED);
display.setState(JFrame.NORMAL);
Is there any way to make this work? Thanks in advance, john murano
Call the requestFocus()
method.
This is not guaranteed to work, because there are many reasons why an operating system would not allow a frame to have focus. There could be another frame with higher priority in a different application. There are also some linux desktops which (if I recall correctly) do not allow frames to request focus.
To give you a better chance of success, I also recommend calling the toFront()
method before requesting focus.
frame.setVisible(true);
frame.toFront();
frame.requestFocus();
Please keep in mind, none of this is guaranteed because frame handling, especially with focus and layering, is very operating system-dependant. So set the frame to visible, move it to the front, and request the focus. Once you give up the EDT, the operating system will likely give the frame the focus. At the very least, the window should be on top.