0

So I am trying to get the currently focused window using KeyboardFocusManager, I made two methods to try and achieve this:

public static void getWindowName() {
    String WindowName = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow().toString();
    System.out.println("Currently opened window: "+WindowName);
}

This results in Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.awt.Window.toString()" because the return value of "java.awt.KeyboardFocusManager.getFocusedWindow()" is null

and

public static Window getActiveWindow() {
    return KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
}

When calling this method using System.out.println(getActiveWindow());, null gets print out to the console. I always have intelliJ opened and focused when executing the program, I even tried to focus another program, the task manager, same results. Does this happen to you too? What can I do to solve this or are there other, better and easier methods to get the currently focused window in java? I am using java 15.0.2 on windows 10

2five
  • 135
  • 1
  • 2
  • 11
  • `System.out.println(javax.swing.FocusManager.getCurrentManager().getActiveWindow().getClass().getSimpleName());` – DevilsHnd - 退職した Feb 11 '21 at 23:51
  • `Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.getClass()" because the return value of "javax.swing.FocusManager.getActiveWindow()" is null` – 2five Feb 12 '21 at 13:52

1 Answers1

0

As java doc said, "getFocusedWindow() return null if the focused Window is not a member of the calling thread's context" then it may happened when you call it from another thread. So, to make sure getFocusedWindow() is fine, try to do focus programmatically:

some_focusable_component.requestFocus();
System.out.println("Currently opened window: "+KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow().toString() );