Search code examples
javaswinghig

JDialog cancel button


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.


Solution

  • 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:

    int optionType = JOptionPane.DEFAULT_OPTION;
    int messageType = JOptionPane.PLAIN_MESSAGE; // no standard icon
    
    JButton ok = new JButton("ok");
    JButton cancel = new JButton("cancel");
    //add any handlers to the buttons
    ...
    //construct options
    Object[] selValues = { ok, cancel };
    
    //show dialog as normal, selected index will be returned.
    int res = JOptionPane.showOptionDialog(null, "message",
            "title", optionType, messageType, null, selValues,
            selValues[0]);