Home Ask Login Register

Developers Planet

Your answer is one click away!

Dennis von Eich February 2016

Why do we need converters for TextFormatters

My professor said that it is 'ideal' to use a filter and a converter for a TextFormatter. I looked at his examples and tried them, but couldn't understand why we need a converter at all.

From the docs:

A Formatter describes a format of a TextInputControl text by using two distinct mechanisms:

A filter (getFilter()) that can intercept and modify user input. This helps to keep the text in the desired format. A default text supplier can be used to provide the intial text.

A value converter (getValueConverter()) and value (valueProperty()) can be used to provide special format that represents a value of type V. If the control is editable and the text is changed by the user, the value is then updated to correspond to the text.

I am cleary something missing here. I get why you want to convert a string to an integer (for calculations etc.). But why do you have to have it as a part of TextFormatter? Can't we just use getText() and then just cast the text as we want to have the value?

One more thing: If we have a filter that doesn't allow non-numeric characters, then why do we need to take care of the conversion of the text to integer/double etc. with a converter?

Maybe I am just missing something very obvious.

Answers


James_D February 2016

You can't cast a String to an Integer (or any other type, except an Object): you have to convert it. Even if the text formatter has a filter that only allows numeric entry, the text field's getText() method still returns a string, which is usually not very convenient (as the entry in the text field likely represents a numeric value in some object).

You might need to get the integer (for example) value represented by the text field in many different places, so you centralize the conversion code in one place by including the converter as part of the formatter.

Additionally, the formatter's value is an observable property, so you can easily bind other properties to it, etc. This would be tricky if you needed to perform the conversion in a binding on the text field's text property.

Post Status

Asked in February 2016
Viewed 1,809 times
Voted 12
Answered 1 times

Search




Leave an answer


Quote of the day: live life