How to focus a JFrame?

感情迁移 提交于 2019-11-27 15:07:56

Have you consider setting the score in the same frame as the game frame?

Other possible ( quick and dirty ) option is to create them in reverse order, or at least ( if score depends on game ) display them in reverse order.

score.setVisible( true );
game.setVisible( true );

My guess is that currently they are:

game.setVisible( true );
score.setVisible( true );

Toggle alwaysOnTop

See here:

http://forums.sun.com/thread.jspa?threadID=5124278

Read about toFront in the API http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Window.html#toFront

Some platforms may not permit this VM to place its Windows above windows of native applications, or Windows of other VMs.

On Windows OS for example toFront causes the icon on the Task Bar to flicker, but the window stays in the back.

The only think that will force the window to front is setAlwaysOnTop.

frame.setAlwaysOnTop(true); 
frame.setAlwaysOnTop(false);

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.

The way that I would do is:

 frame.toFront();
 frame.setState(Frame.NORMAL); 

and If you also want have more control on it you should use requestFocuse.

BTW, here is an example : http://coding.derkeiler.com/Archive/Java/comp.lang.java.gui/2006-06/msg00152.html

Just add the following line of code above the JOptionPaneMessageDialog code ... this.setAlwaysOnTop(false);

Kiran
frame.setExtendedState( JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);

Try the above..

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