I'm developing a java swing application. I wish to achieve such result: press shortcut to let the app window show up. press shortcut again or click otherwhere to let the app hide.
I use jkeymaster to register to listen the event of global shortcut and it works well. But when the user focus on some other window, like chrome, office... the focus window will be other application. Then if the user use the shortcut. My app windows will still show up but cannot gain focus. Could anyone help me to solve it. Here's my code snippet.
Provider provider = Provider.getCurrentProvider(true);
// bind shortcut
provider.register(KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), x -> {
homePage.setVisible(!homePage.isVisible());
if(homePage.isVisible()){
// TODO: 2020/10/1 request focus here
homePage.requestFocusInWindow();
homePage.requestFocus();
KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
focusManager.clearGlobalFocusOwner();
log.info("hasFocus? " + homePage.hasFocus());
log.info("isActive? " + homePage.isActive());
}
});
What I have tried:
- requestFocus and requestFocusInWindow, doesn't work
- I read the source code of requestFocus. It says
* This method cannot be used to set the focus owner to no Component at
* all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code>
* instead.
So I tried focusManager.clearGlobalFocusOwner() but it still doesn't work.