Bind label with two different values-javafx

青春壹個敷衍的年華 提交于 2019-12-13 01:05:31

问题


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.


回答1:


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
}



回答2:


Bindings.format can be used for this purpose:

ansQuesLbl.textProperty().bind(Bindings.format("%d/%d",
                                               answerConnector.noOfAnswersProperty(),
                                               answerConnector.noOfQuestionsProperty()));


来源:https://stackoverflow.com/questions/48862027/bind-label-with-two-different-values-javafx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!