计算填充文本框的百分比

Calculate % of textbox filled in

我正在开发一个 javafx 项目,我在其中提供了一个要填充的文本框 in.I 想要计算填充的文本框的百分比..比如说 100 个字符是一个限制,50 个已填充所以 50 应该是 % 值,但它应该会随着我不断输入而自动更改。我不知道该怎么做(特别是自动的东西)。我想像这样在进度条上显示 % 值: (忽略按钮)

需要帮忙!提前谢谢你

您可以为自己定义一个 DoubleBinding 绑定到 textProperty 并且在每次更改时重新评估它的值。

final double max = 100;
TextField text = new TextField();
DoubleBinding percentage = new DoubleBinding() {
    {
        super.bind(text.textProperty());
    }
    @Override
    protected double computeValue() {
        return text.getText().length() / max;
    }
};

DoubleBinding 的静态初始化程序块中,您绑定 TextFieldtextProperty。这将导致通过 computeValue 方法重新评估绑定。然后你可以将它绑定到 Label:

textProperty
Label lbl = new Label();
lbl.textProperty().bind(percentage.asString());

当然你也可以将它绑定到除 Label 之外的其他控件,例如 ProgressBarProgressIndicator:

ProgressBar bar = new ProgressBar();
bar.progressProperty().bind(percentage);
ProgressIndicator indicator = new ProgressIndicator();
indicator.progressProperty().bind(percentage);

此绑定可用于显示已填写的百分比。您也可以查看此 documentation by Oracle。此绑定的类型是 low-level 绑定。