首先在Scene Builder中设计好表格后
为填充数据构建实体类
package cn.edu.scau.cmi.panjiaru.hibernata.domain;
import javafx.beans.property.SimpleStringProperty;
public class Student {
/** 学生学号ID(主键) **/
private final SimpleStringProperty ID;
/** 学生姓名 **/
private final SimpleStringProperty name;
/** 导师姓名 **/
private final SimpleStringProperty tutorName;
public Student(String ID, String name, String tutorName) {
this.ID = new SimpleStringProperty(ID);
this.name = new SimpleStringProperty(name);
this.tutorName = new SimpleStringProperty(tutorName);
}
public String getID() {
return ID.get();
}
public String getName() {
return name.get();
}
public String getTutorName() {
return tutorName.get();
}
public void setID(String ID) {
this.ID.set(ID);
}
public void setName(String name) {
this.name.set(name);
}
public void setTutorName(String tutorName) {
this.tutorName.set(tutorName);
}
}
注意一定要有成对且命名正确的getter和setter
然后在Controller中,利用ObservableList对表格进行数据填充
private void fillTableView() {
Student student = new Student("1","zhangsan","lisi");
final ObservableList<Student> data = FXCollections.observableArrayList(student);
studentIDCol.setCellValueFactory(new PropertyValueFactory<>("ID"));
tutorNameCol.setCellValueFactory(new PropertyValueFactory<>("tutorName"));
studentNameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
studentTableView.setItems(data);
}
其中studentIDCol,tutorNameCol和studentNameCol对于Scene Builder中的TableView(studentTableView)中的TableColumn
运行结果: