I have a problem: I need to create a TableView where i display all the number of deaths by different diseases within a year. The problem is that, in each row, i need to specify the Province field that is stored in the Deaths Class. When i try to build the different columns of the TableView i use every field of Deaths but with the field Province i need to use a specific method/field inside Province that is getName()/name.
@FXML
private TableView<DecessiAnnuali> decessiTableView;
@FXML
private TableColumn<DecessiAnnuali,Integer> decessiIdColumn;
@FXML
private TableColumn<DecessiAnnuali, String> decessiProvinciaColumn;
@FXML
private TableColumn<DecessiAnnuali,Integer> decessiAnnoColumn;
@FXML
private TableColumn<DecessiAnnuali,Integer> decessiIncidentiStradaliColumn;
@FXML
private TableColumn<DecessiAnnuali,Integer> decessiMalattieTumoraliColumn;
@FXML
private TableColumn<DecessiAnnuali,Integer> decessiMalattieCardiovascolariColumn;
@FXML
private TableColumn<DecessiAnnuali,Integer> decessiMalattieContagioseColumn;
private final DecessiAnnualiService decessiAnnualiService = new DecessiAnnualiService();
@Override
public void initialize(URL location, ResourceBundle resources) {
decessiIdColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
decessiAnnoColumn.setCellValueFactory(new PropertyValueFactory<>("anno"));
decessiProvinciaColumn.setCellValueFactory(new PropertyValueFactory<>("provincia"));
decessiIncidentiStradaliColumn.setCellValueFactory(new PropertyValueFactory<>("incidentiStradali"));
decessiMalattieTumoraliColumn.setCellValueFactory(new PropertyValueFactory<>("malattieTumorali"));
decessiMalattieContagioseColumn.setCellValueFactory(new PropertyValueFactory<>("malattieContagiose"));
decessiMalattieCardiovascolariColumn.setCellValueFactory(new PropertyValueFactory<>("malattieCardiovascolari"));}
As you can see, there is a column that cointains "provincia" (Province in english). When i display the table it obviously prints the toString() String of Province(contained in DecessiAnnuali(AnnualDeaths in english)). I just need to get the name field contained in Province, not the whole toString.
I'm assuming you have a Provincia
class, and the getProvincia()
method in DecessiAnnuali
returns an instance of the Provincia
class.
Given this, you first need to fix the type of your column:
@FXML
private TableColumn<DecessiAnnuali, Provincia> decessiProvinciaColumn;
Then you can define a cellFactory
for your provincia column, in addition to the cellValueFactory
. (The cellValueFactory
determines what to display in the cell, the cellFactory
determines how to display it.)
decessiProvinciaColumn.setCellValueFactory(new PropertyValueFactory<>("provincia"));
decessiProvinciaColumn.setCellFactory(column -> new TableCell<DecessiAnnuali, Provincia>() {
@Override
protected void updateItem(Provincia provincia, boolean empty) {
super.updateItem(provincia, empty);
if (empty || provincia == null) {
setText("");
else {
setText(provincia.getName());
}
}
});