- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements