user1090694
user1090694

Reputation: 639

ObservableList conception for regular variables (without TableView)

In the every example I find for JavaFX there is TableView (with setCellValueFactory on TableColumn and setItems on TableView).

How can I do a single observable object?

For example, if I have following fxml (values would be changed by a third party controller):

<fx:root type="GridPane" xmlns:fx="http://javafx.com/fxml" fx:controller="AStringAndAnIntController">
    <Label text="random string" GridPane.columnIndex="0" GridPane.rowIndex="0"/>
    <Label fx:id="str" GridPane.columnIndex="0" GridPane.rowIndex="1"/>
    <Label text="random int" GridPane.columnIndex="1" GridPane.rowIndex="0"/>
    <Label fx:id="integer" GridPane.columnIndex="1" GridPane.rowIndex="1"/>
</fx:root>

and an model object:

public class AStringAndAnInt{
    private String str;
    private int integer;
    //with its setters and getters
}

What should I do in the controller to link my object with JavaFX controls?

public class AStringAndAnIntController extends GridPane implements Initializable{
    @FXML Label str;
    @FXML Label integer;

    @Override public void initialize(URL arg0, ResourceBundle arg1){
    }
    public void setAStringAndAnInt(AStringAndAnInt strint){
        //what would go inside? a ObserbableList.add(strint)?
    }
}

Upvotes: 1

Views: 394

Answers (1)

Sergey Grinev
Sergey Grinev

Reputation: 34498

You need to use JavaFX properties and binding to have observable values.

public class AStringAndAnInt{
    private StringProperty str = new SimpleStringProperty();
    private IntegerProperty integer = new SimpleIntegerProperty();

    public String getStr() {
        return str.getValue();
    }

    public void setStr(String value) {
        str.set(value);
    }

    public StringProperty strProperty() {
        return str;
    }

    public int getInteger() {
        return integer.getValue();
    }

    public void setInteger(int value) {
        integer.set(value);
    }

    public IntegerProperty integerProperty() {
        return integer;
    }
}    

So in your controller you can write:

public class AStringAndAnIntController extends GridPane implements Initializable{
    @FXML Label str;
    @FXML Label integer;

    @Override public void initialize(URL arg0, ResourceBundle arg1){
    }
    public void setAStringAndAnInt(AStringAndAnInt strint){
        str.textProperty().bind(strint.strProperty());
        integer.textProperty().bind(strint.integerProperty().asString());
    }
}

Upvotes: 1

Related Questions