Reputation: 491
I have a live javafx
user application which has a label : No of answers/No of questions
,
No of answers increases as the user answers the question, and number of questions increases as one class throws questions to user.
Label initially looks like - 0/0
I want to bind two different variables (NumberOfAnswers, NumberOfQuestions)
to this label, say if I have 10 questions thrown to user and user has answered 2 it should look like : 2/10
Label ansQuestLbl = new Label("0/0");
if (answerConnector!= null) {
log.info("Going to bind , No of answers: "+answerConnector.getNoOfAnswers());
ansQuesLbl.textProperty().bind(answerConnector.getNoOfAnswers().asString());
log.info("Bound number of answers with label on UI");
}
This only binds Number of answers to the label.
Thanks in advance.
Upvotes: 1
Views: 729
Reputation:
All you need is Bindings.concat(Object... args)
:
For example:
IntegerProperty noOfAnswers = answerConnector.noOfAnswersProperty();
IntegerProperty noOfQuestions = answerConnector.noOfQuestionsProperty();
ansQuesLbl.textProperty().bind(Bindings.concat(noOfAnswers, "/", noOfQuestions));
Or:
IntegerProperty noOfAnswers = answerConnector.noOfAnswersProperty();
IntegerProperty noOfQuestions = answerConnector.noOfQuestionsProperty();
ansQuesLbl.textProperty().bind(noOfAnswers.asString().concat("/").concat(noOfQuestions.asString()));
Note: To avoid problems with the Properties I would recommand to follow the javafx naming convention, so that the class for answerConnector
should look like this:
public class AnswerConnector {
private final IntegerProperty noOfAnswers = new SimpleIntegerProperty(0);
public IntegerProperty noOfAnswersProperty() {
return noOfAnswers;
}
public int getNoOfAnswers() {
return noOfAnswers.get();
}
public void setNoOfAnswers(int noOfAnswers) {
this.noOfAnswers.set(noOfAnswers);
}
// same for noOfQuestions
}
Upvotes: 4
Reputation: 82531
Bindings.format
can be used for this purpose:
ansQuesLbl.textProperty().bind(Bindings.format("%d/%d",
answerConnector.noOfAnswersProperty(),
answerConnector.noOfQuestionsProperty()));
Upvotes: 2