How to activate a window in Java?

I would like to activate my Swing application programmatically. I want to say that I would like to write code that makes me JFramevisible and focused (the window title should be highlighted). I tried to use requestFocus(). It works only if the application has at least 2 windows A and B: A is hidden, B is visible. Now, if I call A.requestFocus(), it becomes active as I want. This does not happen if the application has only one window or if both windows are invisible.

I found 2 workarounds.

  • use a fake transparent unscreened frame that is always on top. This fake window will play the role of window B. I have not tried to implement it, but it seems that it should work.
  • a challenge A.setAlwaysOnTop(true). This brings window A on top of other windows. But that is not the focus. Use java.awt.Robot(mouseMove, mousePress, mouseRelease) to click the title bar of window A. Now call A.setAlwaysOnTop(false)and move the mouse cursor back to the previous position. I implemented the code and it works, but it looks like an ugly workaround.

Is there a “right” solution?

+6
source share
5 answers

I figured this one should help you.

+1
source
frame.setState(Frame.NORMAL); // restores minimized windows
frame.toFront(); // brings to front without needing to setAlwaysOnTop
frame.requestFocus();

for everything you might know in excruciating detail, see this page: http://www.developer.com/java/other/article.php/3502181/Window-Focus-and-State-in-Java.htm

+5
source

:

frame.setSelected(true);

, , try/catch...

, , :

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

frame.setVisible(true);
frame.setVisible(true); // Yes you need this second one
+1
source

I was in the same boat - none of these works worked.

"MY" was as follows:

thisFrame.getWindowListeners()[0].windowActivated(
     new WindowEvent(
              thisFrame,
              WindowEvent.WINDOW_ACTIVATED
     )
);
schedulesTable.requestFocus();

thisFrame = the window to get activated

schedulesTable = my component in the window I wanted to get focus for
+1
source

I found this solution to the problem:

//frame - JFrame
frame.setExtendedState(JFrame.ICONIFIED);
frame.setExtendedState(JFrame.NORMAL);
frame.toFront();
frame.requestFocus();

In my configuration (win 7, java 12) - it works fine and stable

+1
source

All Articles