Search code examples
javajavafxratingcontrolsfx

set Rating value to text box


Here I'm Using rating feature of ControlsFX. Each time rating value 's altered, I need to update the value in TextField as shown in screen shot. Is it possible to use javafx.concurrent.Task here? and how can I apply it? enter image description here

here's my code:

@FXML
private HBox ratinghbox;
@FXML
private TextField yourratingtxt;
private Rating rating;

@Override
public void initialize(URL url, ResourceBundle rb) {
    rating = new Rating();
    rating.setPartialRating(true);
    ratinghbox.getChildren().add(rating);
    yourratingtxt.setText(String.valueOf(rating.getRating()));
}

Solution

  • Using change listener

    Use the ratingProperty to update the Textfield

    rating.ratingProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> observable,
                    Number oldValue, Number newValue) {
            textField.setText(newValue.toString()); 
        }
    });
    

    Using Binding

    You can also create a bidirectional binding between the textfield and rating (Only if you are good with not editing the value of the textfield )

    textfield.setDisable(true)
    Bindings.bindBidirectional(textField.textProperty(), rating.ratingProperty(),
                new NumberStringConverter());
    

    If you have to edit the textfield, do not use this