简体   繁体   中英

How to bind a StringProperty to a BigDecimal?

I have a ChangeListener that when triggered, a findGPA() method is called.

private void findGPA(){
    GPA = gradeCre/sum;
    decGPA = new BigDecimal(GPA);
    decGPA = decGPA.setScale(2, RoundingMode.CEILING);
    System.out.println("Your average GPA is: " + decGPA);
}

The BigDecimal is initialized as follows:

private BigDecimal decGPA = BigDecimal.ZERO;

In the initialize() method:

SubmitStageBorderPane.setBottom(AddStackCircle());

which calls:

private StackPane AddStackCircle(){

    StackPane stackCircle = new StackPane();
    StringProperty gpa = new SimpleStringProperty("");
    gpa.bind(new SimpleStringProperty(decGPA.toString()));

    Text avgGPA = createText("Your semester GPA is: " + gpa);
    Circle resultCircle = createCircle(avgGPA);

    stackCircle.getStyleClass().add("stackCircle");
    stackCircle.getChildren().addAll(resultCircle, avgGPA);

    return stackCircle;
}

private Circle createCircle(Text avgGPA){

    Circle resultCircle = new Circle();
    resultCircle.setFill(Color.GREEN);
    resultCircle.setStroke(Color.GREY);
    resultCircle.setStrokeWidth(3);
    resultCircle.setRadius(getWidth(avgGPA) / 2 + 10);

    return resultCircle;
}

private Text createText(String text){

    Text avgGPA = new Text(text);
    avgGPA.setBoundsType(TextBoundsType.VISUAL);
    avgGPA.getStyleClass().add("avgGPA");

    return avgGPA;
}

However, when i run it, it produces the following label text Your semester GPA is: StringProperty[bound, invalid] , and it doesn't change even when the value of decGPA changes.

For the text to update, you'd need to bind the text of the Text node instead of simply setting the text. Furthermore you should bind it to a property that is actually updated, not just a property that will never be modidfied (like new SimpleStringProperty(decGPA.toString()) ).

Assuming the findGPA method is properly called, it should be implemented like this:

private final ObjectProperty<BigDecimal> decGPA = new SimpleObjectProperty(BigDecimal.ZERO);

private void findGPA(){
    GPA = gradeCre/sum;
    decGPA.set(BigDecimal.valueOf(GPA).setScale(2, RoundingMode.CEILING));
    System.out.println("Your average GPA is: " + decGPA.get());
}

private Text createText(ObservableValue<String> textExpression){

    Text avgGPA = new Text();
    avgGPA.textProperty().bind(textExpression);
    avgGPA.setBoundsType(TextBoundsType.VISUAL);
    avgGPA.getStyleClass().add("avgGPA");

    return avgGPA;
}
Text avgGPA = createText(decGPA.asString("Your semester GPA is: %s"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM