Search code examples
javaswingescapingkey-bindingsenter

jdialog enter and escape not working


Context: I'm trying to create modal JDialog and pretty much replicate JOptionPane functionality with custom buttons with one condition - i don't want to use UIManager to set windows style.

Problem: JDialog doesn't answer to ESCAPE and ENTER keys like it's supposed to. I've tried all proposed solutions i could find online (multiple listeners solutions, setting default button etc.) and i can't get it to work.

Whole class is uploaded to pastebin at http://pastebin.com/Kcj82h2i

Actual key settings in extended JDialog class are done with

InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = getRootPane().getActionMap(); 

inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "returnyes");
actionMap.put("returnyes", new ResultYes());

inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "returnno");
actionMap.put("returnno", new ResultNo());

And the dialog gets called from JFrame with the following code:

if (results == 1)
{
    InvoiceLinesTableModel tm = (InvoiceLinesTableModel) tbl_invoiceItems.getModel();
    InvoiceLinesTableRow row = tm.getRow(tbl_invoiceItems.getSelectedRow());
    tm.deleteRow(row);
    tm.fireTableDataChanged();
    StaticFunctions.updateTableRowHeights(tbl_invoiceItems);
}

Help?


Solution

  • As the JDialog is modal the call to addCustomKeyMaps() will be blocked when the window becomes visible. You should make this call before you call setVisible(true).