esuslogo
 [To advertise Java(tm) Events here, contact joris@esus.com!]
banner

Java™
by example!






New @ Esus.com


  gb  In-house search engine for better results!

  gb  Get updates with the esus.com
newsletter!









  Home 
 Browse Categories 
 Ask a Java Question 
 Help 
  For Java Tips & Tricks, subscribe to the esus.com newsletter!
Search Java Q&A, Links, API's:   adv 

How do I have 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




Further Information
Author of answer: coyoteblue

Comments to this answer are only viewable by members. Login or become a member!





Terms of Service | Privacy Policy | Contact

Copyright © 2000-2003 Esus.com - All Rights Reserved 
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. Esus.com is independent of Sun Microsystems, Inc. All other trademarks are the sole property of their respective owners.