Detecting Focus on (frame + components) in swing

风流意气都作罢 提交于 2019-12-23 21:04:41

问题


I have a small dialog frame that appears, and within this frame are a series of buttons and a textbox. I need the frame to be able to detect when the user has put focus on something else on the screen (being: anything besides the frame and its components), so I can close down the frame. Any advice on how to go about this? I've been trying at focus solutions for hours, to no solution!


回答1:


need the frame to be able to detect when the user has put focus on something else on the screen

Use a WindowListener and listen for windowDeactivated.




回答2:


Try using a WindowStateListener

The WindowEvent parameter it provides can tell you if the window has lost focus through the getNewState() method.

class MyFocusLostListener implements WindowStateListener {

    public void windowStateChanged(WindowEvent e) {
        if (e.getNewState() == WindowEvent.WINDOW_LOST_FOCUS) {
            e.getWindow().setVisible(false);
        }
    }
}



回答3:


listen to property changes of the property "permanentFocusOwner" of the KeyboardFocusManager. On being notified, check if the new focusOwner is in the child hierarchy under the frame, if not - close the frame.

Edit: seeing the answers suggesting a Window/StateListener - they are better than mine for a top-level window :-) Listening to the keyboardFocusManager is a good approach for containers deeper down in the hierarchy, implemented f.i. in the CellEditorRemover of a JTable (to decide if a pending edit should be terminated)



来源:https://stackoverflow.com/questions/5717716/detecting-focus-on-frame-components-in-swing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!