0
votes

I want to display all Prisoners data into a single TableView. A prisoner looks like that (all the code is a sample) :

public class Prisoner {
    private String id;
    private String name;
    private PrisonerCase case;
    Prisoner() {
        id = "Unknown";
        name = "Unknown";
        case = new PrisonerCase();
    }
}

public class PrisonerCase {
    private String id_case;
    private String date_case;
    PrisonerCase() {
        id_case = "unknown";
        date_case = "unknown";
    }
}

Then I have my TableView : data is an ObservableList<Prisoner> and return all the prisoners I have in my database. I build all prisoners and all the prisoner cases in the function getData().

TableView tv = new TableView();
data = Database.getData();
TableColumn id_column = new TableColumn("ID");
id_column.setCellValueFactory(new PropertyValueFactory<Prisoner, String>("id"));

This works fine, but my question is, how can I add the case in the TableView ? I tried

TableColumn n_case_column = new TableColumn("N° Case");
n_case_colmun.setCellValueFactory(new PropertyValueFactory<PrisonerCase, String>("id_case"));

But it doesn't work. Of course, I didn't forget to add all the columns to the TableView at the end.

tv.setItems(data);
tv.getColmuns().addAll(id_column, n_case_column);
1
I think you should add columns to table view before items so your code should be tv.getColmuns().addAll(id_column, n_case_column); tv.setItems(data); Also you should specify columns type such as TableColumn<Prisoner,String> columnName - Anas
The fact to add columns before items didn't solve anything. But thank you for the columns types - NicoTine

1 Answers

4
votes

First, never use raw types. The type of the TableView is the type of the objects representing each row (Prisoner in this case). The types of the TableColumns are, first, the type of the TableView, and second, the type of the data displayed in each cell in that column.

So you should have

TableView<Prisoner> tv = new TableView<>();
TableColumn<Prisoner, String> idColumn = new TableColumn<>("ID");
TableColumn<Prisoner, String> nCaseColumn = new TableColumn<>("N° Case");

You didn't show the methods in your classes; I am going to assume you follow standard Java naming conventions (I changed some of your variable names above to conform to these too). Then you can do

idColumn.setCellValueFactory(cellData -> 
    new SimpleStringProperty(cellData.getValue().getId()));
// or 
// idColumn.setCellValueFactory(new PropertyValueFactory<>("id")); 
// but the first version above is better, imho

nCaseColumn.setCellValueFactory(cellData -> 
    new SimpleStringProperty(cellData.getValue().getCase().getIdCase()));