17

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.

Branislav Lazic
  • 14,388
  • 8
  • 60
  • 85

1 Answers1

21

Try:

txtId.textProperty().bindBidirectional(authorProps2.authorsIdProperty(), new NumberStringConverter());
James_D
  • 201,275
  • 16
  • 291
  • 322
  • 1
    @Hendrikto Try `txtId.textProperty().bind(authorProps2.authorsIdProperty().asString())` – James_D Aug 02 '16 at 00:05
  • @James_D I want to bind an IntegerProperty to a TextField though. Excactly the opposite of that. – Hendrikto Aug 03 '16 at 02:17
  • Use [`Bindings.createIntegerBinding(...)`](http://docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/Bindings.html#createIntegerBinding-java.util.concurrent.Callable-javafx.beans.Observable...-) – James_D Aug 03 '16 at 02:24