How can we set the shortcut key to a JButton in Java?


A JButton is a subclass of AbstractButton and it can be used for adding platform-independent buttons to a Java Swing application. A JButon can generate an ActionListener interface when the button is pressed or clicked, it can also generate the MouseListener and KeyListener interfaces. We can also set the short cut keys for a JButton using the setMnemonic() method.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonTest extends JFrame {
   private JButton button;
   public JButtonTest() {
      setTitle("JButtonTest");
      button = new JButton("Click or press ALT-C");
      button.setMnemonic('C');
      add(button, BorderLayout.CENTER);
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
            JOptionPane.showMessageDialog(null, ("Button clicked or pressed"));
         }
      });
      setSize(475, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String args[]) throws Exception {
      new JButtonTest();
   }
}

Output

In the above program, if we click or apply short cut key (Alt+C from the keyboard) on JButton, a new popup window can be generated below


Updated on: 10-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements