Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate all fields in Swing GUI

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.

like image 888
Chinthaka Manathunga Avatar asked Nov 24 '12 17:11

Chinthaka Manathunga


4 Answers

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);
like image 54
Reimeus Avatar answered Oct 12 '22 15:10

Reimeus


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:

  • Kenai Simple Validation API

  • InputVerifier

  • http://www.java2s.com/Code/Java/Swing-Components/InputVerifierExample.htm

like image 40
paulsm4 Avatar answered Oct 12 '22 14:10

paulsm4


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

like image 2
vels4j Avatar answered Oct 12 '22 16:10

vels4j


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.

like image 1
Aniket Inge Avatar answered Oct 12 '22 14:10

Aniket Inge