How can I assign hotkeys for a Button or JButton?
Created May 4, 2012
Iryna Issayeva To assign hotkeys or shortcut keys to JButton or any other component inherited from AbstractButton (such as JRadioButton or JCheckBox), use method setMnemonic(char mnemonic) or setMnemonic(int mnemonic).
Here is the pattern:
For example:
jButton1.setMnemonic('M'); jCheckBox.setMnemonic(KeyEvent.VK_M);
The AWT components like Button can't do it directly but you can do a little trick by adding the KeyListener to the top container which contains your Button. In addition you need somehow to underline correspondent letter in the Button's label( but this is another trick with fonts...).
... buttonPush = new Button("Push"); buttonPush.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doSomeAction(); }}); buttonPush.getParent().addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); if ( c == 'M' || c == 'm' ) doSomeAction(); }}); ...