Setting the Default Button in Swing

  

Consider you have a form with several text fields and some buttons. One of the buttons is usually the “default” button , which would get executed if the user pressed enter, while the focus is in any of the text fields in that form. You should have definitely seen this type of buttons. As an example in google.com, you can type you query in the textfield and press enter, which is same as clicking the “Google Search” button.
  While most people who implement this, add a keylistener to each textfield and execute the doClick() method in JButton when the Enter key is pressed, there is an easier way. Also by implementing this by setting up the listener, you will not be able to tell swing to let it do OS level special effects like the “pulsing” effect in a MAC or a border-effect on windows.

  So what to do?simple. The RootPane has a method setDefaultButton() to which you can pass the default button as the argument and which will be considered the default button.

So here’s the code to set the default button “button1″ for a frame “frame1″

frame1.getRootPane().setDefaultButton(button1);

 A corresponding method “isDefaultButton() ” is present in the JButton class to check if this is the default button.

easy?







One Response to 'Setting the Default Button in Swing'

  1. shaul - July 9th, 2008 at 8:29 pm

    Thanks a lot.
    I was just looking to implement something like this. But wasn’t aware of this feature. By luck I stumbled upon your post.

    Thanks again,
    Shaul


Leave a Reply





Popular Articles

Blog Categories

Monthly Archives

Resources