java - FXML:将 TableViews 项目属性绑定(bind)到 Controller

标签 java javafx binding fxml

我在 FXML 中有一个 TableView,我想将它的 items 属性绑定(bind)到 Controller 中的列表(就像在 WPF 中一样) ),我的 FXML 代码是这样的:

<TableView fx:controller="controllers.MyController"  items="$controller.loggings">
    <columns>
        <TableColumn text="Nom">
            <cellValueFactory>
                <PropertyValueFactory property="name" />
            </cellValueFactory>
        </TableColumn>

        <TableColumn text="Type">
            <cellValueFactory>
                <PropertyValueFactory property="type" />
            </cellValueFactory>
        </TableColumn>
    </columns>
</TableView>

我的 Controller 如下:

public class MyController {
    public ObservableList<Logging> loggings = FXCollections.observableArrayList();

    @FXML
    protected void initialize(){
        loggings.add(new Logging(){{
            setName("hilton");
            setType("hotel");

        }});
    }
}

由于某种原因,异常启动。我做错了什么?

最佳答案

您尚未声明 fx 命名空间:

<TableView xmlns:fx="http://javafx.com/fxml/1" fx:controller="controllers.MyController"  items="$controller.loggings">
    ...
</TableView>

此外, Controller 类需要包含 logging 字段的 getter:

private final ObservableList<Logging> loggings = FXCollections.observableArrayList();

public ObservableList<Logging> getLoggings() {
    return loggings;
}

注意:JavaFX 不考虑表达式绑定(bind)的字段,因此需要 getter。

关于java - FXML:将 TableViews 项目属性绑定(bind)到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40831566/

相关文章:

java - 我如何使用子类中的父类方法

java - 数组列表的数组?

java - 如何用更好的解决方案替换 switch 语句 - 干净的代码提示

java - 从填充了 CheckMenuItems 的 MenuButton 访问信息 (JavaFX)

c# - WPF - 以编程方式绑定(bind)到 DataGridCheckBoxColumn

WPF MultiBinding - UnsetValue 问题

WPF C# 如何在代码中创建 THIS 绑定(bind)?

java - 无法运行程序 "osascript": error=2, 没有这样的文件或目录

javafx - 如何从 ToggleGroup 获取选定的单选按钮

Java:控制线程速度/线程的更改延迟