javafx - 如何调用绑定(bind)属性的方法

标签 javafx model-binding

我知道如何绑定(bind)属性,但是如何绑定(bind)函数的调用?

例如:我有一个指向文件的ObjectProperty。现在,我想将路径绑定(bind)到其文件夹?如果 ObjectProperty 的值为 C:\\user\Desktop\text.txt,则绑定(bind)应指向 C:\\user\Desktop >.

我想我可以在绑定(bind)中调用 getParentFile()

最佳答案

有很多方法可以映射 ObjectProperty ,看看类(class) Bindings .

(所有示例均假设您有 ObjectProperty<File> file )

  1. Bindings.createObjectBinding(Callable<T> func, Observable... dependencies)

    ObjectBinding<File> parent = Bindings.createObjectBinding(() -> {
        File f = file.getValue();
        return f == null ? null : f.getParentFile();
    }, file);
    
  2. Bindings.select(ObservableValue<?> root, String... steps)

    ObjectBinding<File> parent = Bindings.select(file, "parentFile");
    

    file 时,这将在错误流上打印警告为空。

您还可以创建自己的映射方法(类似于 createObjectBinding ):

public static <T,R> ObjectBinding<R> map(ObjectProperty<T> property, Function<T,R> function) {
    return new ObjectBinding<R>() {
        {
            bind(property);
        }
        @Override
        protected R computeValue() {
            return function.apply(property.getValue());
        }
        @Override
        public void dispose() {
            unbind(property);
        }
    };
}

并使用它

ObjectBinding<File> parent = map(file, f -> f == null ? null : f.getParentFile());

关于javafx - 如何调用绑定(bind)属性的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50167280/

相关文章:

java - 如何强制 JavaFX 应用程序中的所有按钮使用我的自定义皮肤?

Java setCellValueFactory lambda 表达式(当可能为 null 时)

user-interface - 如何在 JavaFX 场景中定位按钮(或任何 GUI 元素)?

asp.net-mvc - ASP.NET MVC - ID 字段的自定义模型绑定(bind)器

asp.net-mvc-3 - TinyMCE 模型绑定(bind)回发

android - 代码 fragment 的 Mvvmcross 绑定(bind)子项

java - 如何阻止 Javafx 上的文本溢出

java - 是否可以在 JavaFX 的 WebView 中确定元素位置?

c# - ASP.Net MVC : Submit array/collection in a single parameter

asp.net-core - ASP.NET Core MVC - 模型绑定(bind) : Bind an interface model using the attribute [FromBody] (BodyModelBinder)