Um Ihre JComboBox mit einer benutzerdefinierten Nachricht zu validieren, können Sie einfach einen benutzerdefinierten Constraint-Validator erstellen.
Siehe folgendes Beispiel:
MyModel.java
public class MyModel {
@ValidComboBox //this is the annotation which validates your combo box
private String question;
//getter and setter
}
ValidComboBox.java // Anmerkung
import java.lang.annotation.*;
import javax.validation.*;
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ComboBoxValidator.class)
@Documented
public @interface ValidComboBox {
String value = "Please select a security question";
String message() default "Please select a security question.";
Class<?>[]groups() default {};
Class<? extends Payload>[]payload() default {};
}
ComboBoxValidator.java
import javax.validation.*;
public class ComboBoxValidator implements ConstraintValidator<ValidComboBox, String> {
private String value;
@Override
public void initialize(ValidComboBox arg0) {
this.value = arg0.value;
}
@Override
public boolean isValid(String question, ConstraintValidatorContext arg1) {
if(question.equalsIgnoreCase(value)){
return false;
}
return true;
}
}
hinzufügen Artikel zu Ihrem JComboBox wie folgt aus:
JComboBox<String> jComboBox = new JComboBox<>();
jComboBox.addItem("Please select a scurity question");
jComboBox.addItem("Question 1");
jComboBox.addItem("Question 2");
Und folgende Zeilen, die Sie hinzufügen müssen, wenn Sie Aktion ausführen zu überprüfen:
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
String question = jComboBox.getSelectedItem().toString();
MyModel model = new MyModel();
model.setQuestion(model);
Set<ConstraintViolation<MyModel>> constraintViolations = validator.validate(model);
if (!constraintViolations.isEmpty()) {
String error = "";
for (ConstraintViolation<MyModel> constraintViolation : constraintViolations) {
error += constraintViolation.getMessage();
JOptionPane.showMessageDialog(null, error);
}
}
Es wird angezeigt Bitte wählen Sie eine Sicherheitsfrage Nachricht, wenn Sie versuchen, Anfrage ohne Frage zu senden.