9

I have a Question. I created a Swing GUI Form. This form contain JTextFields, JComboBox components.

Now what i want to do, when user pressing completed button i want to validate JTextFields and JComboBox component. I want to write common method for all JTextFields and another common method for JComboBoxes. Does anyone know about validate API?

I dont need to validate all fields one by one.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

4 Answers4

8

One option here would be to use Swing's InputVerifier to validate input for every JComboBox & JTextField used. You could share common verifiers between components:

   public class MyNumericVerifier extends InputVerifier {
        @Override
        public boolean verify(JComponent input) {
           String text = null;

           if (input instanceof JTextField) {
             text = ((JTextField) input).getText();
           } else if (input instanceof JComboBox) {
             text = ((JComboBox) input).getSelectedItem().toString();
           }

           try {
              Integer.parseInt(text);
           } catch (NumberFormatException e) {
              return false;
           }

           return true;
        }

        @Override
        public boolean shouldYieldFocus(JComponent input) {
           boolean valid = verify(input);
           if (!valid) {
              JOptionPane.showMessageDialog(null, "Invalid data");
           }

           return valid;
       }
    }

InputVerifier verifier = new MyNumericVerifier()
comboBox.setInputVerifier(verifier);
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • +1 You can provide feedback in `shouldYieldFocus()`, for [example](http://stackoverflow.com/a/13510756/230513). – trashgod Nov 24 '12 at 18:03
6

If "validation" means "check all the fields" ... then, yes - your "validate" routine will check all the fields one-by-one :)

You can also "validate-as-you-go". There are many ways to accomplish this, including:

paulsm4
  • 114,292
  • 17
  • 138
  • 190
2

There are some third party api's available. You can develop your own for

  1. Required field,
  2. Email Validation,
  3. Max & Min length, etc.,

Here is a sample tutorial for Building a Swing Validation Package with InputVerifier

vels4j
  • 11,208
  • 5
  • 38
  • 63
1

That's not possible. Instead you will have to create a new class that inherits the JTextField and then have a validate() function as private or protected, and call that everytime you getText() (which means you'll have to @Override it)from it.

An alternate is to use Container.getComponent() and check for instanceof and then validate each field separately. This however is against what you're asking for.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78