Confirm all fields in Swing GUI

I have a question. I created a Swing GUI form. This form contains components JTextFields, JComboBox.

Now, what I want to do, when the user clicks the completed button, I want to check the JTextFields and the JComboBox component. I want to write a generic method for all JTextFields and another common method for JComboBoxes. Does anyone know about API validation?

I do not need to check all the fields one by one.

+6
source share
4 answers

If "check" means "check all fields" ... then yes, your "check" will check all fields one at a time :)

You can also "check how-you-go." There are many ways to do this, including:

+5
source

One option here is to use the Swing InputVerifier to check input for all used JComboBox and JTextField . You can use 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); 
+6
source

There are several third party api. You can design your own for

  • Obligatory field,
  • Email verification
  • Max. and Min. length etc.

Here is an example tutorial for Creating a Swing Validation Package Using InputVerifier

+1
source

It's impossible. Instead, you will need to create a new class that inherits JTextField, and then will have the function validate() as private or protected , and call it every time you getText() (this means you will need @Override it) from him.

An alternative is to use Container.getComponent() and check for instanceof , and then check each field separately. However, this is contrary to what you are asking for.

0
source

All Articles