How to focus a JFrame?

后端 未结 6 928
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 18:05

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

相关标签:
6条回答
  • 2020-12-03 18:19

    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 );
    
    0 讨论(0)
  • 2020-12-03 18:23

    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.

    0 讨论(0)
  • 2020-12-03 18:28

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

    0 讨论(0)
  • 2020-12-03 18:29

    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);
    
    0 讨论(0)
  • 2020-12-03 18:37

    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

    0 讨论(0)
  • 2020-12-03 18:38
    frame.setExtendedState( JFrame.MAXIMIZED_BOTH);
    frame.setVisible(true);
    

    Try the above..

    0 讨论(0)
提交回复
热议问题