常规变量的ObservableList概念(没有TableView)

时间:2013-02-27 11:26:20

标签: java javafx-2 fxml

在我为JavaFX找到的每个示例中都有TableViewsetCellValueFactory上有TableColumnsetItems上有TableView

我如何做一个可观​​察对象?

例如,如果我有以下fxml(值将由第三方控制器更改):

<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>

和一个模型对象:

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

我应该在控制器中将我的对象与JavaFX控件链接起来?

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)?
    }
}

1 个答案:

答案 0 :(得分:1)

您需要使用JavaFX properties and binding来获得可观察的值。

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;
    }
}    

所以在你的控制器中你可以写:

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());
    }
}