绑定到对象的javafx属性,该属性可以为null [英] Binding to javafx properties of a object that can be null

查看:58
本文介绍了绑定到对象的javafx属性,该属性可以为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的控制器:

I have a controller like this:

public class ItemController {
    @FXML TextField name;
    @FXML TextField description;
    private City city = null;

    @FXML public void initialize () {
        name.textProperty().bind(city.nameProperty());
        description.textProperty().bind(city.descriptionProperty());
    }

    public void searchById(int idCity) {
           //get a city by its id, it returns null if not found
           city = Backend.getCity(idCity);
    }
}

如您所见,city最初被分配为null,而searchById将其分配给新值,我想在其具有有效值时创建对city属性的绑定,但随后不将文本属性设置为空(也许取消绑定这些字段,但我不确定)并禁用这些字段,但是我不知道如何执行此操作,在此先感谢您的帮助.

As you see city is initially assigned to null, and searchById assigns it to a new value, I want to create a bind to properties of city when it has a valid value but it's not then set the text properties to empty (perhaps unbinding the fields but I'm not sure) and disable the fields, but I don't have a good idea how to do it, thanks in advance for any help.

推荐答案

您不仅需要在 name 更改时更改绑定,而且在 city 更改时更改绑定.为此, city 本身必须是可观察的.

You need the binding to change not only if the name changes, but also if the city changes. For this to happen, city itself must be observable.

// private City city = null;
private ObjectProperty<City> city = new SimpleObjectProperty<>();

现在,您的文本字段必须绑定到属性的属性".标准库中对此有一些有限的API,但是它编写得不好,并且对null值的处理非常糟糕.我建议您使用第三方库来实现这种功能. ReactFX 内置了此功能,您可以

Now your text field has to be bound to a "property of a property". There is some limited API for this in the standard libraries, but it is not well written and handles null values extremely badly. I recommend you use a third party library for this kind of functionality. ReactFX has this functionality built in, and you can do

@FXML public void initialize () {
    name.textProperty().bind(Val.flatMap(city, City::nameProperty).orElseConst(""));
    name.disableProperty().bind(city.isNull());

    // ...
}

对于双向绑定,您可以这样做

For bidirectional binding you can do

name.textProperty().bindBidirectional(Val.selectVar(city, City::nameProperty));

这篇关于绑定到对象的javafx属性,该属性可以为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆