Reputation: 235
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
Upvotes: 0
Views: 262
Reputation: 332
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() );
Upvotes: 0