I noticed the setUserData
method that appears on almost all JavaFX objects and I was wondering if there are specific uses for this that are considered better coding practice than others. (Or if there are at least uses that would be considered improper.)
On the Java API the description is:
Convenience method for setting a single Object property that can be retrieved at a later date.
Is this method really just for convenient attaching of whatever your heart desires to JavaFX objects? I could see its usefulness in tagging/marking objects, but does it have any other standard uses?
Userdata
is normally used when the controls can be toggled between selected and non-selected states.
Such controls include
For single selection, we need to assign these objects to togglegroups
. Since we cannot directly access the objects of the Controls from the toggle group, we assign these controls with userdata
, which can be accessed from the Toggle
using getUserData
method.
Let us consider a scenario where we have two RadioButton
s for Gender. The requirement is to show
Male
Female
but, the data that is to be transferred should be
M
F
Under such scenarios, you can use something like
final ToggleGroup group = new ToggleGroup();
RadioButton male = new RadioButton("Male");
male.setToggleGroup(group);
male.setUserData("M");
RadioButton female = new RadioButton("Female");
female.setToggleGroup(group);
female.setUserData("F");
group.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
public void changed(ObservableValue<? extends Toggle> ov,
Toggle old_toggle, Toggle new_toggle) {
if (group.getSelectedToggle() != null) {
System.out.println(group.getSelectedToggle().getUserData().toString());
}
}
});
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