Home > Net >  Check if a Swing form does not contain empty fields
Check if a Swing form does not contain empty fields

Time:10-17

I want to determine if a form containing: JTextField, JDatePicker, JComboBox, JSpinner, does not contain empty fields. I have several forms with different fields that I would like to be evaluated with a common method without managing the order of the fields to work with any sequence of fields.

My purpose would be to create a method like:

if method (field1, field2, field3) {
...
}
if method (field4, field5) {
...
}

I don't want to do multiple methods for multiple forms.

CodePudding user response:

You could do as @camickr mentioned in a comment above:

Create an ArrayList of components you want to validate. Then you iterate through the ArrayList checking if each component. When you find an empty component you return false.

And you could check for the type of field they are and then check if they are empty / not selected.

private boolean isFormValid(List<JComponent> components) {
    for (int i = 0; i < components.size(); i  ) {
        if (components.get(i) instanceof JTextField) {
            if (components.get(i).getText().isEmpty()) {
                return false;
            }
        }
        if (components.get(i) instanceof JComboBox) {
            if (components.get(i).getSelectedItem() == null) {
                return false;
            }
        }
        // Add checks for other components you want to check here
    }
    return true;
}

CodePudding user response:

Polymorphism should be used.

For that you'll need an abstract verifier. Validating Input shows how to write an InputVerifier for each type of field in each of your forms. Then each concrete InputVerifier will have a verify() that you can invoke on each JComponent in the form. When it's time to verify the form, given a List<JComponent> list, you can verify the entire form like this:

boolean b = true;
for (JComponent field : list) {
    b &= field.getInputVerifier().verify(field);
}
b &= someOtherFormLevelPredicate;
…
  • Related