Search code examples
javaswingjcomboboxinputverifier

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.


Solution

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