Having the Enter key activate the default button on a JDialog

Use getRootPane() and setDefaultButton to make a button on a JDialog respond to the ‘enter’ key. I’ve included code that allows which ever button has focus to be the default.

   ... begin snippet ...
   JButton ok = new JButton("OK");
   JButton cancel = new JButton("CANCEL");
 
   //kicks off when component gains focus
   ok.addFocusListener(new buttonfocusEventHandler());
 
   //kicks off when component gains focus
   cancel.addFocusListener(new buttonfocusEventHandler()); 
 
   ... end snippet ...

   class buttonfocusEventHandler extends FocusAdapter {

      /** Checks buttons on dialog for focus
       * and makes that button the default
       * 
       * @param evt Holds event
       */
      public void focusGained(FocusEvent evt) {
 
         JButton button = (JButton) evt.getSource();
           
         if (button == ok) {
            JRootPane root = getRootPane();
            root.setDefaultButton(button);
         } //end if
            
         if (button == cancel){
            JRootPane root = getRootPane();
            root.setDefaultButton(button);
         } // end if
      }             
}  //  end buttonfocusEventHandler