问题
Is there an easy way to validate
a group of JTextFields
in Java
. I am currently using sqlite manager
, neatbeans IDE
to create a simple form that collects information to add a job into the database. I realise there is too many JTextFields. How can I validate each JTextFields either through sqllite throwing an exception error which can be customised, or maybe in Neatbeans through properties dialogue box. Validation is to be presence check, i.e. has a value been entered. Custom validation message?
回答1:
Use an InputVerifier
, as shown in How to Use the Focus Subsystem : Validating Input. There's a related example here, among others.
回答2:
+1 t trashgods answer.
You could also use:
- DocumentFilter/DocumentListener and add it to
JTextField
.
See here for an example and this variation.
DocumentFilter
allows you to validate text before showing changes i.e by calling super.XXX
implementation of overridden method after validating text successfully) where as DocumentListener
does not. It usually in most cases better to settle for DocumentFilter
.
See here for more help:
- How to Write a Document Listener
- Implementing a Document Filter
or alternatively:
JFormattedTextField
see here for an example.
来源:https://stackoverflow.com/questions/14170232/form-validation-for-jtextfield-in-java