问题
I'm trying to implement a textfield like this one :
TextField Validation http://imageshack.com/a/img537/8329/FSht8P.png
My goal is to identify if the text of the TextField is a Double
or something else (then it appears in red).
I want to use ControlsFX to learn the library and to not edit the css, but it doesn't work very well, and I'm lost in the javadoc. Does anyone have an example or can help me improve my code ?
Here what I tried to do :
Validator<Double> checkTextField = new Validator<Double>() {
@Override
public ValidationResult apply(Control t, Double u) {
ValidationResult vd = new ValidationResult();
if(Double.valueOf(t.toString()) != null){
vd.addErrorIf(t, "false", false);
}
return vd;
}
};
ValidationSupport validationSupport = new ValidationSupport();
validationSupport.registerValidator(latitudeTextField, checkTextField/*Validator.createEmptyValidator("Text is required")*/);
ValidationDecoration iconDecorator = new GraphicValidationDecoration();
ValidationDecoration cssDecorator = new StyleClassValidationDecoration();
ValidationDecoration compoundDecorator = new CompoundValidationDecoration(cssDecorator, iconDecorator);
validationSupport.setValidationDecorator(compoundDecorator);
回答1:
You indeed make several mistakes. First you can have a look at the ControlsFX Showcase. There are always several code examples within their showcase.
Next your example expects the TextField to serve a Double to the Validator, but as you problably know the TextField itself only operates with Strings, so you will need a String Validator.
Then you try whatever control.toString() will print, which is most likely not the text it represents but some information about the control itself. What you want is the Text, which is currently shown in the textfield. For that you will not have to ask the control, since the text-value is already given to you in form of the value parameter 'u' in your case.
So what you want to do now is, you want to check, if the String could be parsed into a double. From the Documention you can find a Regex to check if this is the case (don't know if there are any better regexes for your case).
So all together it could look like this:
ValidationSupport support = new ValidationSupport();
Validator<String> validator = new Validator<String>()
{
@Override
public ValidationResult apply( Control control, String value )
{
boolean condition =
value != null
? !value
.matches(
"[\\x00-\\x20]*[+-]?(((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*" )
: value == null;
System.out.println( condition );
return ValidationResult.fromMessageIf( control, "not a number", Severity.ERROR, condition );
}
};
support.registerValidator( textfield, true, validator );
来源:https://stackoverflow.com/questions/29607080/textfield-component-validation-with-controls-fx