Reputation: 19
I am building a football league management system, I built the user interface using javaFx, I created this class to populate the table using a database.
public class TableHandler {
public static ObservableList<Team> getTeams() {
ObservableList<Team> list = FXCollections.observableArrayList();
DBConnection db;
try {
db = new DBConnection();
String sql = "Select * from teams";
ResultSet result = db.read(sql);
while (result.next()) {
list.add(new Team(result.getInt(1), result.getString(2), result.getString(3), result.getInt(4),
result.getDouble(5)));
}
} catch (Exception e) {
e.getMessage();
}
return list;
}
public static TableView<Team> getTable(ObservableList<Team> list) {
TableView<Team> table;
TableColumn<Team, String> idColumn = new TableColumn<>("ID");
idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
TableColumn<Team, String> nameColumn = new TableColumn<>("Name");
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
TableColumn<Team, String> phoneNumberColumn = new TableColumn<>("phoneNumber");
phoneNumberColumn.setCellValueFactory(new PropertyValueFactory<>("phoneNumber"));
TableColumn<Team, Integer> pointsColumn = new TableColumn<>("Points");
pointsColumn.setCellValueFactory(new PropertyValueFactory<>("points"));
TableColumn<Team, Double> budgetColumn = new TableColumn<>("Budget");
budgetColumn.setCellValueFactory(new PropertyValueFactory<>("budget"));
table = new TableView<>();
table.setItems(list);
table.getColumns().addAll(idColumn, nameColumn, phoneNumberColumn, pointsColumn, budgetColumn);
return table;
}
and I created a button to add teams to the table by the user, what I can't figuer out is how to refresh the table when the user hit the add button, any help would be appriciated.
Upvotes: 0
Views: 40
Reputation: 3501
You don't have to. The very idea of an observable list is that the TableView
observes for changes in it and renders the value change accordingly.
The thing you have to make sure of is that you're adding elements to the collection that was actually bound to the TableView
and not some other one. You didn't post the code that adds the items, so it's hard to tell, but if you're using getTeams()
and then adding to that, then it's wrong (since it's a new ObservableList
and not the one bound to the TableView
). You should always be using table.getItems().add(...)
to add items to a TableView
.
Upvotes: 2