I am developing a java swing application. I want to add a keyboard shortcut say CTRL + H. This should perform the same action performed by jButton1 when clicked.
This shortcut should behave in the same way even when jButton1 is not focused.
I tried with KeyEventDispatcher, but it doesn't seem to be working for me. Is there any other way?
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);
}
}
}
};
I think the answer to your question can be found here http://docs.oracle.com/javase/6/docs/api/javax/swing/JComponent.html#registerKeyboardAction%28java.awt.event.ActionListener,%20java.lang.String,%20javax.swing.KeyStroke,%20int%29
You should look into Key Bindings, using classes KeyStroke
and InputMap
. From Oracle's TextComponentDemo
(slightly modified, but still using DefaultEditorKit as example):
// CTRL + H
KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_H, Event.CTRL_MASK);
// bind the keystroke to an object
inputMap.put(key, DefaultEditorKit.backwardAction);
Use them over Key Listeners when you want the event fired even when the component doesn't have the focus:
Instead of using the Control key explicitly as a modifier, use the MASK
returned by getMenuShortcutKeyMask()
for a better cross-platform user experience. ImageApp
is an example.
来源:https://stackoverflow.com/questions/11529195/custom-keyboard-shortcut-in-java