views:

504

answers:

3

Hi,

In HTML forms, if you press 'enter' while in a text field the form will generally submit.

I'm implementing a search panel in Java Swing, and I want to include the same functionality as I think users will be expecting this.

I know that it's possible to use setAction on a JTextField to accomplish this, however I was wondering if there was an easier / better way than setting the action on every field. I've tried looking around but there doesn't seem to be a standard solution to this problem that I can find!

Edit: There is getRootPane().setDefaultButton(...), but that only seems to set the default button for a frame. That wouldn't work for me as I'm using a tabbed pane, each panel of which has a form on it!

+2  A: 

You may have to listen for the tab switch and reset the default button for the current tab using getRootPane().setDefaultButton(...).

Clint
And you would use a ChangeListener to listen for the tab switch.
camickr
+1  A: 

We have the same problem in one of our applications.

You can add a Key Listener to the JTextField's editor:

txtField.getEditor().getEditorComponent().addKeyListener(new java.awt.event.KeyAdapter()
{
  @Override
  public void keyTyped(final KeyEvent e)
  {
    super.keyTyped(e);

    // Check if the user pressed Enter
    if (e.getKeyChar() == '\n')
    {
      // Action here/button press here
    }
  }
});
thedude19
the dude abides.
akf
-1 - You would not use a KeyListener to listen for the Enter key on a JTextField. You either use an ActionListener or the setAction method.
camickr
A: 

IIRC, adding an ActionListener to the JTextField will provide the functionality you want

quick google later...

Yep - and this appears to be the recommended way by Sun, as shown in the text field trail...

MrWiggles