JavaFX 8 - 如何将TextField文本属性绑定到TableView整数属性

17
假设我有这样一种情况:我有一个名为 tableAuthors 的表格视图 (TableView),其中包含两个列 (TableColumns) (Id 和 Name)。
这是 AuthorProps POJO,它被 TableView 使用:
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;


public class AuthorProps {
    private final SimpleIntegerProperty authorsId;
    private final SimpleStringProperty authorsName;


    public AuthorProps(int authorsId, String authorsName) {
        this.authorsId = new SimpleIntegerProperty(authorsId);
        this.authorsName = new SimpleStringProperty( authorsName);
    }

    public int getAuthorsId() {
        return authorsId.get();
    }

    public SimpleIntegerProperty authorsIdProperty() {
        return authorsId;
    }

    public void setAuthorsId(int authorsId) {
        this.authorsId.set(authorsId);
    }

    public String getAuthorsName() {
        return authorsName.get();
    }

    public SimpleStringProperty authorsNameProperty() {
        return authorsName;
    }

    public void setAuthorsName(String authorsName) {
        this.authorsName.set(authorsName);
    }
}

假设我有两个TextFields(txtId和txtName)。现在,我想将表格单元格中的值绑定到TextFields上。
 tableAuthors.getSelectionModel()
                .selectedItemProperty()
                .addListener((observableValue, authorProps, authorProps2) -> {
                    //This works:
                    txtName.textProperty().bindBidirectional(authorProps2.authorsNameProperty());
                    //This doesn't work:
                    txtId.textProperty().bindBidirectional(authorProps2.authorsIdProperty());
                });

我可以将名称TableColumn绑定到txtName TextField,因为authorsNameProperty是一个SimpleStringProperty,但是我无法将Id TableColumn绑定到txtId TextField,因为authorsIdProperty是一个SimpleIntegerProperty。我的问题是:如何将txtId绑定到Id TableColumn
附言:如果需要,我可以提供工作示例。
1个回答

21

尝试:

txtId.textProperty().bindBidirectional(authorProps2.authorsIdProperty(), new NumberStringConverter());

1
@Hendrikto 请尝试使用 txtId.textProperty().bind(authorProps2.authorsIdProperty().asString()) - James_D
@James_D 我想要将一个 IntegerProperty 绑定到 TextField,正好与之相反。 - Hendrikto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接