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.
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);
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
There are some third party api's available. You can develop your own for
Here is a sample tutorial for Building a Swing Validation Package with InputVerifier
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With