可以定義爲百姓餐桌這樣一個模式:
public class People {
public People(String firstName, String lastName){
this.firstName = new SimpleStringProperty(firstName);
this.lastName = new SimpleStringProperty(lastName);
}
private StringProperty firstName;
public void setFirstName(String value) { firstNameProperty().set(value); }
public String getFirstName() { return firstNameProperty().get(); }
public StringProperty firstNameProperty() {
return firstName;
}
private StringProperty lastName;
public void setLastName(String value) { lastNameProperty().set(value); }
public String getLastName() { return lastNameProperty().get(); }
public StringProperty lastNameProperty() {
return lastName;
}
}
然後定義一個方法,你檢索數據:
private ObservableList<People> fetchPeople(Connection con) throws SQLException {
logger.info("Fetching people from database");
ObservableList<People> people = FXCollections.observableArrayList();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from people");
while (rs.next()) {
people.add(new People(rs.getString("first_name"), rs.getString("last_name")));
}
return people;
}
此方法返回一個ObservableList<People>
,您可以使用它來填充tableView例如:
Connection conn = getConnection();
ObservableList<People> people = fetchPeople(conn);
ObservableList<TableColumn> columns = tableView.getColumns();
columns.get(0).setCellValueFactory(new PropertyValueFactory("firstName")); // asumming this column is the corresponding to firstName, you can also set an id to the column an refer to it with @FXML property
columns.get(1).setCellValueFactory(new PropertyValueFactory("lastName")); // asumming this column is the corresponding to lastName, you can also set an id to the column an refer to it with @FXML property
tableView.setItems(people);
使用這種方法:setCellValueFactory(new PropertyValueFactory("firstName"));
我們在模型綁定屬性firstNameProperty
在TableView
中的相應列。
此外,您可以使用函數來創建單元格中所需的值。如果你想要第三個欄,顯示的全名,這是你可以得到它:
columns.get(2).setCellValueFactory(param -> {
People p = (People)((CellDataFeatures) param).getValue();
return new SimpleStringProperty(p.getFirstName() + " " + p.getLastName());
});
參見[如何填充正在在FXML文件中定義的TableView中(http://stackoverflow.com/問題/ 11180884 /如何填充一個tableview-that-is-defined-in-an-fxml-file-that-is-in-in)爲零件「填充你的問題的表」。 「檢索數據」部分是Java的核心。搜索關於它的教程。但要成爲用檢索到的數據更新JavaFX GUI的工具。即,DB抓取必須位於除JavaFX主線程以外的其他線程中。爲此,使用JavaFX服務和任務。再次搜索「JavaFX:background periodic sql quering」,「JavaFX:GUI凍結數據庫查詢」等.GL。 –
謝謝。抱歉,我沒有看到該線程。下次研究會更好:) – rfmind
沒問題。搜索時請參閱「高級搜索提示」。這是你可以相信我的救星。 –