Difference between methods to close JFrame and JDialog after keyboard event

4

I need to deploy to a desktop application built using swing , a way for the JFrame master to close the application when the user clicks ESC , and the JDialogs daughters of this%

asked by anonymous 17.02.2016 / 17:09

1 answer

3

After performing tests with the two ways suggested in the answers quoted in the question, some conclusions about the two modes:

Using KeyboardFocusManager

Using the KeyboardFocusManager class, as suggested by @ utluiz ♦, the event is "listening" to all keyboard actions, in any component of the Frame and also of other windows which this Frame serves as a reference. In the case of the question, JDialogs also invoke the event, if the ESC key is pressed, closing the application even though the method has only been implemented in the parent parent frame, and it is out of focus by cause of JDialog .

This behavior is interesting if you want the key to be a "wildcard shortcut" in the application, but in the case of the particular question, it causes unwanted behavior, because if you press this key to quit editing a component as a JTable cell, the application is also closed immediately.

Using AbstractAction

As suggested in @renan's response, using AbstractAction , the event does not interfere inside a cell of JTable , like the example mentioned above, and does not "listen" to the keyboard in other child windows, probably because it is only added as a root panel event of that Frame .

Although having a slightly greater complexity to add this type of event to windows compared to the previous method (to work in all windows, should be added in each separately), in my case this option ended up because it does not affect edits in the cells of JTable of the application and also because of the possibility of having the pressed key just close the window in focus at the moment, and not finish the application.

    
18.02.2016 / 12:18