简体   繁体   中英

How to focus JDialog programmatically?

I have read some of those similar threads here but they did not help me. I have my JDialog that is undecorated and initially is unfocusable:

super(connectionsTree.getMainFrame(), "", false);
        super.setUndecorated(true);
        super.setFocusableWindowState(false);
        super.setFocusable(false);
super.getContentPane().add(scrollPane);
        super.pack();

Now whenever this dialog is visible and user tpes Space button I must make that JDialog focused so that it receives key events. I do it like so :

if (keyCode == 32) {
            tooltip().setFocusable(true);
            tooltip().setFocusableWindowState(true);
            tooltip().requestFocusInWindow();
        }

This code makes my JDialog focusable but JDialog is not focused and key events are not grasped by it. tooltip() method only returns instance of my JDialog.

How to make my JDialog receive focus programmatically?

Thank you!

According to documentation of requestFocusInWindow() focus to Component will be granted only if top level parent component is focus owner. So this will not work if your main window has no focus on it. You should use Component#requestFocus() instead. From Component#requestFocus() description

Requests that this Component get the input focus, and that this Component's top-level ancestor become the focused Window.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM