Ok - First I don't think there is a way to set application wide shortcuts in Java Swing(Refer this question). But for a component it is possible.
You have to use a create an Action
for the KeyStroke
. But for Windows I found this library very helpful.
{
KeyStroke cancelKeyStroke = KeyStroke
.getKeyStroke((char) KeyEvent.VK_ESCAPE);
Keymap map = JTextComponent.getKeymap(JTextComponent.DEFAULT_KEYMAP);
map.addActionForKeyStroke(cancelKeyStroke, cancelKeyAction);
}
private static Action cancelKeyAction = new AbstractAction() {
public void actionPerformed(ActionEvent ae) {
Component comp = (Component) ae.getSource();
Window window = SwingUtilities.windowForComponent(comp);
if (window instanceof Dialog) {
window.dispose();
} else if (comp instanceof JTextComponent
&& !(comp instanceof JFormattedTextField)) {
JTextComponent tc = (JTextComponent) comp;
int end = tc.getSelectionEnd();
if (tc.getSelectionStart() != end) {
tc.setCaretPosition(end);
}
}
}
};