- 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 to set default button for JFrame in Java?
To set default button for JFrame, use the setDefaultButton() method −
JFrame frame = new JFrame(); frame.getRootPane().setDefaultButton(button);
The following is an example to set default button for JFrame −
Example
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.JButton; import javax.swing.JFrame; public class SwingDemo { public static void main(String args[]) { JButton button = new JButton("Demo Button!"); JFrame frame = new JFrame(); frame.setSize(500, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getRootPane().setDefaultButton(button); button.setMnemonic(KeyEvent.VK_A); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { System.out.println("Button pressed!"); button.setEnabled(!button.isEnabled()); } }); frame.add(button); frame.setVisible(true); } }
Output
On pressing the above button, the following is displayed on Console −
Advertisements