- 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 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 −
- Related Articles
- How to set FlowLayout for JFrame in Java?
- How to set the location of a button anywhere in JFrame?
- How to set minimum size limit for a JFrame in Java
- How to disable close button on a JFrame in Java?
- How to close JFrame on the click of a Button in Java
- How to set default background color for JTextPane in Java?
- How can we disable the maximize button of a JFrame in Java?
- How to set location of JLabel in a JFrame with Java?
- How to maximize JFrame in Java Swing
- How to set default value for empty row in MySQL?
- How to set the value for the attribute layout_weight for button in Android dynamically from java code?
- How to set default text encoded for android webview?
- How to activate and deactivate JFrame in Java
- How to change JFrame background color in Java
- How to add background Image to JFrame in Java

Advertisements