Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

java - How to focus a JFrame?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...