开发者

How to trigger Java Swing InputVerifier on enter in JComboBox (actionPerformed)?

I have a Swing JComboBox with an InputVerifier set correctly.

I am using the combo box to set an integer.

If I type "cat" in the field and hit tab, my InputVerifier triggers and resets the value to "0".

If I type "cat" and hit enter, my InputVerifier is never called from actionPerformed. Do I need to explicitly call开发者_运维问答 my InputVerifier from actionPerformed?

What's the best model to validate my JComboBox on tab and enter? It seems like this is something that should be given to me "for free" by the swing model.


The problem is "hit Tab" and "hit Enter" mean two different things in Java Swing. But those two actions mean the same thing to you, me, and the user.

Swing has no single mechanism to detect "when the user is done entering data". Instead, Swing focuses on the mechanics of "is this field losing keyboard focus" and "is the user pressing Enter key while inside a field".

Semantically those two actions mean the same thing from the user's perspective: "I'm done. Here's my input.". But, from what I can tell, Swing fails to offer a way to detect that user intention. I'm as surprised as you by the lack of such a feature, as this seems to be the most basic function of a form in a GUI. What we need, but don't have, is a "dataEntered" event.

There is a workaround…

In a similar context (JTextField instead of JComboBox) the Sun/Oracle Java Tutorial provides the example InputVerificationDemo where a class is created that:

  • Extends InputVerifier (to handle tabbing/clicking where focus is about to be lost)
  • Implements ActionListener (to handle pressing Enter key without leaving field)

The good thing about this workaround is that you can locate your handling code all in one place. The downside is that you still have the hassle of:

  • Creating a separate class.
  • Instantiating that class.
  • Passing that instance to both the setInputVerifier and addActionListener methods of your widget (JTextField, etc.).


This is the expected behavior of InputVerifier: the TAB key attempts to change focus, while the ENTER key does not. You can bind the ENTER key to a different action, as described in the tutorial How to Use Key Bindings. Also, consider the informative article Key Bindings, which includes a handy utility application.


When using an editable combo box, focus is on a JTextField which is used as the editor of the combo box. You can add an ActionListener to this text field.

In the ActionListener you could try invoking the transferFocus() method which should be equivalent to tabbing our of the text field. If that doesn't work then tha actionListener should invoke the same editing code as the InputVerifier.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜