Question

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!

Was it helpful?

Solution

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...

OTHER TIPS

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

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
    }
  }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top