Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

2 Answers
Samual Sam

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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.