How can I assign hotkeys for a Button or JButton?

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).

For example:


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...).

Here is the pattern:

buttonPush = new Button("Push");
buttonPush.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {

buttonPush.getParent().addKeyListener(new KeyAdapter() {
   public void keyTyped(KeyEvent e) {
      char c = e.getKeyChar();
      if ( c == 'M' || c == 'm' )

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact