javafx -- TableView的使用

总览

首先需要一个Model类来构建数据结构和方法,然后创建一个Observablelist来与TableView绑定,Observablelist中存储Model类的对象。

下面是例子:

Model class

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public Person {
    public Person(String id, String name){
        this.setId(id);
        this.setName(name);
    }

    private StringProperty id;  //也可以在这里直接new
    public void setId(String value){ idProperty().set(value);}
    public String getId(){ return idProperty().get(); }
    public StringProperty idProperty(){
        if(id == null) id = new SimpleStringProperty(this, "id");
        return id;
    }

    private StringProperty name;
    public void setName(String value){ nameProperty().set(value);}
    public String getName(){ return idProperty().get(); }
    public StringProperty nameProperty(){
        if(name == null) name = new SimpleStringProperty(this, "name");
        return name;
    }
}

所有属性使用对应的Property属性,每个属性对应三个函数:get(), set(), Property(),其中Property方法用于获得变量。
除了上面的写法,也可以声明变量的时候直接new,这样Property()方法只需要return。

Controller class

    @FXML
    private TableView<Person> personTable;
    @FXML
    private TableColumn<Person, String> idColumn;
    @FXML
    private TableColumn<Person, String> nameColumn;

    //用于保存数据,<>中为上面Model类的类名
    private ObservableList<Person> personData = FXCollections.observableArrayList();

    /**
    * 在fxml文件完成载入时自动被调用
    */
    @FXML
    private void initialize(){
        idColumn.setCellValueFactory(cellData -> cellData.getValue().idProperty());
        nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());

        //绑定数据到TableView
        personTable.setItems(personData);

        //添加数据到personData,TableView会自动更新
        personData.add(new Person("007", "爱谁谁"));
    }

猜你喜欢

转载自blog.csdn.net/cccxu_/article/details/80895625