How to set default button for JFrame in Java?

Java 8Object Oriented ProgrammingProgramming

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 −

raja
Published on 08-May-2019 16:24:17
Advertisements