JavaFX 8 - How to bind TextField text property to TableView integer property


Question

Let's say I have a situation like this: I have a TableView (tableAuthors) with two TableColumns (Id and Name).

This is the AuthorProps POJO which is used by 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);
    }
}

And let's say I have two TextFields (txtId and txtName). Now, I would like to bind values from table cells to TextFields.

 tableAuthors.getSelectionModel()
                .selectedItemProperty()
                .addListener((observableValue, authorProps, authorProps2) -> {
                    //This works:
                    txtName.textProperty().bindBidirectional(authorProps2.authorsNameProperty());
                    //This doesn't work:
                    txtId.textProperty().bindBidirectional(authorProps2.authorsIdProperty());
                });

I can bind Name TableColumn to txtName TextField because authorsNameProperty is a SimpleStringProperty, but I can't bind Id TableColumn to txtId TextField because authorsIdProperty is a SimpleIntegerProperty. My question is: How can I bind txtId to Id TableColumn?

P.S. I can provide working example if it's necessary.

1
14
3/24/2014 11:26:07 PM

Accepted Answer

Try:

txtId.textProperty().bindBidirectional(authorProps2.authorsIdProperty(), new NumberStringConverter());
17
3/25/2014 12:29:15 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon