【问题标题】:Bind label with two different values-javafx用两个不同的值绑定标签-javafx
【发布时间】:2018-02-19 08:26:08
【问题描述】:

我有一个实时的javafx 用户应用程序,它有一个标签:No of answers/No of questions, 当用户回答问题时,答案的数量会增加,而问题的数量会随着一个班级向用户提出问题而增加。

标签最初看起来像 - 0/0

我想将两个不同的变量 (NumberOfAnswers, NumberOfQuestions) 绑定到这个标签,假设我有 10 个问题向用户提出并且用户已经回答了 2,它应该看起来像: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");
    }

这只会将 Number of answers 绑定到标签。

提前致谢。

【问题讨论】:

  • getNoOfAnswers()的返回类型是什么?
  • SimpleIntegerProperty
  • setNoOfAnsers 的 setter 是什么样子的?

标签: java javafx label


【解决方案1】:

您只需要Bindings.concat(Object... args):

例如:

IntegerProperty noOfAnswers = answerConnector.noOfAnswersProperty();
IntegerProperty noOfQuestions = answerConnector.noOfQuestionsProperty();
ansQuesLbl.textProperty().bind(Bindings.concat(noOfAnswers, "/", noOfQuestions));

或者:

IntegerProperty noOfAnswers = answerConnector.noOfAnswersProperty();
IntegerProperty noOfQuestions = answerConnector.noOfQuestionsProperty();
ansQuesLbl.textProperty().bind(noOfAnswers.asString().concat("/").concat(noOfQuestions.asString()));

注意:为避免属性出现问题,我建议遵循 javafx 命名约定,以便 answerConnector 的类应如下所示:

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
}

【讨论】:

  • 或者,您可以使用Bindings.format 进行更详细的格式设置。
  • 我正在我的 javafx 场景中尝试它,我是否需要刷新我的场景,因为它与标签绑定但未在我的 UI 上更新?
  • 没有在我的 UI 上更新 是什么意思? noOfAnswersnoOfQuestion 的值在哪里可以更改?顺便把getNoOfAnsers 重命名为noOfAnsersProperty
  • 感谢您的建议,javafx scene 上没有更新,因为答案的值在变化,标签值没有在场景/UI 上更新。
  • 您是否可能不小心更改了answerConnectorgetNoOfAnswers 的对象而不是属性的值?
【解决方案2】:

Bindings.format 可用于此目的:

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

【讨论】:

    猜你喜欢
    • 2013-03-22
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多