Issue
Iam working on a Textfield for numbers. I need to copy the input from one textfield to the other.
What would the difference be between these two:
FieldTwo.setText(FieldOne.getText());
And
FieldTwo.setText(FieldOne.textProperty().getValue());
Solution
The <propertyName>Property()
accessors are used for binding and change or invalidation listeners. That way you can react to future changes to the property.
The getValue()
accessor on the property allows you to get the property value at that time.
When a property is defined, you can just define the property() accessor and the client will have access to the full functionality of the property, including the ability to get and set the current property value. However, it is by convention (and makes code easier to read) if additional getters and setters for the property value are defined on the object defining the property.
The get<propertyName>()
method is just a shorthand for the current property value. It also allows a class with properties to conform to Java bean naming conventions. This is useful in meeting developer expectations for class interfaces and aiding automated tooling, e.g. Jackson or jaxb object serialization or IDE code generation tasks.
Study the property tutorial for more tutorial on defining and using properties.
For your example, use the following if you want the value of fieldOne to be the current value of fieldTwo:
fieldTwo.setText(fieldOne.getText());
Use the following if you want the value of fieldOne to always be the value of fieldTwo, even when fieldTwo changes.
fieldTwo.textProperty().bind(fieldOne.textProperty());
Use the following if you want the value of fieldOne to always be the value of fieldTwo, even when fieldTwo changes and vice versa.
fieldTwo.textProperty().bindBidirectional(fieldOne.textProperty());
Note, when I did this, I followed another naming convention for the property reference, fieldOne
instead of FieldOne
as you have in your question. Always follow Java naming conventions.
So you can see that the different accessors are useful for different access patterns, which is why the library follows conventions to provide access to that functionality. It is advisable that you follow similar conventions for any code you write that defines properties.
Properties in JavaFX can be more subtle than simple read write properties, though those are the most common.
Once you understand simple properties and wish to understand property functionality more fully, study the:
- Property pattern cookbook
- The target of the linked cookbook is advanced users.
- You do not need to understand everything in the linked article to make use of simple properties.
Answered By - jewelsea
Answer Checked By - Senaida (JavaFixing Volunteer)