Java Swing How to - Set default button for JFrame








Question

We would like to know how to set default button for JFrame.

Answer

//from  www. j  ava2s.  c  o m
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 Main {

  public static void main(String args[]) {
    JButton jbtnA = new JButton("java2s.com");

    JFrame jfrm = new JFrame();
    jfrm.setSize(300, 300);

    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jfrm.getRootPane().setDefaultButton(jbtnA);

    jbtnA.setMnemonic(KeyEvent.VK_A);

    jbtnA.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        System.out.println("Alpha pressed. Beta is enabled.");
        jbtnA.setEnabled(!jbtnA.isEnabled());
      }
    });
    jfrm.add(jbtnA);
    jfrm.setVisible(true);
  }
}