Difference between methods to close Jframe and Jdialog after keyboard event

Asked

Viewed 368 times

4

I need to implement in a desktop application built using swing, a way for the JFrame main close the application when user click on ESC, and the JDialogs daughters of this JFrame, close only themselves when tightening ESC.

Researching right here on the sopt, I found this question but some questions regarding the code of the two replies posted by @utluiz and by @Renan, where the former uses a resource that does not override the method windowClosing and the second already overrides this method, delegating the closure to a custom method.

There is a difference between using the AbstractAction and the KeyboardFocusManager for this purpose? Both may affect in some way other listeners used in the application?

1 answer

3


After carrying out some tests with the two forms suggested in the answers cited in the question, to some conclusions regarding the two modes:

Using Keyboardfocusmanager

Using the class KeyboardFocusManager, as suggested by @utluiz , the event is "listening" to all keyboard actions, in any Frame component and also other windows that this Frame serves as reference. In the case of the question, Jdialogs also invoke the event if the key ESC be tight, closing the application even though the method has been implemented only in the main "parent" frame, and this being out of focus because of the JDialog.

This behavior is interesting if you want the key to be a "wildcard shortcut" in the application, but for the specific question, it ends up bringing an unwanted behavior, because if you press this key to exit the editing of a component as a cell of a JTable, the application is also immediately closed.


Utilizing Abstractaction

Already the suggested form in the @Renan response, using AbstractAction, the event does not interfere within a cell of the JTable, as the example cited above, and does not "listen" to the keyboard in other daughter windows, probably because it is added only as event of the root panel of that Frame.

Although it has a little more complexity to add this type of event to the windows compared to the previous method (to work on all windows, it should be added on each separately), for my case this option ended up attending because it does not affect issues in the cells of the JTable of the application and also the possibility to make the button pressed just close the window in focus at the moment, and not finish the application.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.