1

在我为 JavaFX 找到的每个示例中,都有TableView(使用setCellValueFactoryonTableColumnsetItemson 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)?
    }
}
4

1 回答 1

1

您需要使用JavaFX 属性和绑定来获得可观察的值。

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());
    }
}
于 2013-02-27T11:44:12.877 回答