Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper uses of JavaFX setUserData?

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?

like image 673
River Avatar asked Jul 07 '14 17:07

River


1 Answers

Userdata is normally used when the controls can be toggled between selected and non-selected states.

Such controls include

  • RadioButtons
  • ToggleButton
  • RadioMenuItem

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 RadioButtons 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());
    }
  }
});
like image 117
ItachiUchiha Avatar answered Nov 10 '22 02:11

ItachiUchiha