问题
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