Proper use of JavaFX setUserData?

I noticed the setUserData method that appears in almost all JavaFX objects, and I was wondering if there are specific applications for this that are considered to be better coding practices than others. (Or, if there is at least use that will be considered improper.)

The Java API describes the following:

A convenient method for setting a single Object property, which can be obtained later.

Is this method really just convenient for you that your heart desires JavaFX objects? I could see its usefulness in methods / methods, but does it have any other standard uses?

+7
java coding-style javafx
source share
1 answer

Userdata commonly used when controls can switch between selected and unselected states.

Such controls include

  • Radiobuttons
  • ToggleButton
  • RadioMenuItem

For single selection, we need to assign these togglegroups objects. Since we cannot directly access control objects from the switch group, we assign these Userdata controls that can be accessed from Toggle using getUserData .

Consider a scenario in which we must use RadioButtons for Gender. The requirement is to show

 Male Female 

but the data to be transmitted must be

 M F 

In this scenario, 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()); } } }); 
+8
source share

All Articles