How can I set a cancel button in a Swing JDialog
, i.e. a button whose action is performed automatically if the user presses the “Cancel” key on the keyboard?
The counterpart is offered for a default action via the setDefaultButton
method of the dialog's root pane.
If that's helping, I'm searching for an analogue to the WinForms Form.CancelButton
property.
I don't think this is possible with JDialog without extending it.
You could use JOptionPane.showOptionDialog() (or possibly one of the other show methods), passing the JButtons you want to be used.
If the options passed are components, they'll be rendered as normal, so you can do something like this:
Single line solution
where t is any component(except JButton) like JTextField in the dialog.
The best way I can see is to add an
Action
to the action map of the root pane, and link that action to the escape key using the root pane's input map.For this, you need an
Action
. If your cancel button's behaviour is implemented as an action (ie.cancelButton.getAction() != null
), then this will work:Otherwise, if the cancel button's logic is implemented via an
ActionListener
, you could have theactionPerformed()
method of theActionListener
call aprivate void onCancel()
method that implements the logic, and register a "cancel" action that calls the same method.All you have to do is attach the action listener to the button and call
dialog.setVisible(false)
inside of it.