【问题标题】:JavaFX: Binding a property to a label does not updateJavaFX:将属性绑定到标签不会更新
【发布时间】:2015-06-02 10:19:15
【问题描述】:

我正在尝试将 IntegerProperty(我在 getter 中转换为 StringProperty)的值绑定到 javafx 标签。但是,该值不会改变。

在班主任:

private IntegerProperty totalMessaged;

在类的构造函数中:

this.totalMessaged = new SimpleIntegerProperty(0);

类的getter:

public StringBinding getTotalMessaged() { 
    return this.totalMessaged.asString(); 
} 

在我用来增加属性的方法中:

this.totalMessaged.add(1);

在控制器类中:

@FXML
private void initialize() {
    this.sentLabel.textProperty().bind(ClientHandler.getInstance().getTotalMessaged());
}

当我启动程序时,标签将设置为 0,因此绑定似乎首先起作用。但是,当它调用增加属性的方法时,属性不会增加 1,它保持为 0 - 标签不会改变,如果我在使用 this.totalMessaged.add(1) 后将值打印到控制台;它仍然会说这个属性是0。 我做错了什么?

【问题讨论】:

    标签: java user-interface binding properties javafx


    【解决方案1】:

    试试这个方法。使用转换器将字符串转换为整数。

    在控制器中:

    sentLabel.textProperty().bindBidirectional(ClientHandler.getInstance().totalMessagedProperty(), new NumberStringConverter());
    

    在模型中:

    private final IntegerProperty totalMessagedProp = new SimpleIntegerProperty(0);
    
    public int getTotalMessaged() {
        return totalMessagedProp.get();
    }
    
    public IntegerProperty totalMessagedProperty() {
        return totalMessagedProp;
    }
    
    public void setTotalMessaged(int totalMessaged) {
        this.totalMessagedProp.set(totalMessaged);
    }
    

    【讨论】:

    • 感谢您的回答,NumberStringConverter 后来派上了用场,但我的问题是另一个您无法从我提供的源代码中看到的问题。我没有在增加值的任务中使用 Platform.runlater,这就是为什么它不能以某种方式工作。完全是我的错,但还是谢谢你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 2011-01-20
    • 2013-04-09
    相关资源
    最近更新 更多