Search code examples
javauitableviewjavafxrow

Get particular row of tableView item which has some condition (JavaFX)


I am making attendance TableView for one person. I am getting tableView row and if person in that specific day has status "present" (string) then I want to change that particular row and change its background-color to green.

Then if he is "absent" in that particular day I want to change that row and set red background.

Otherwise if there is no date and status in row I need to change row again and set white background.

PROBLEM: It is going through first if statement and then set every row green because first statement is "true".

I want to get only rows with present and set only that rows to green background colour.

*getStatus returns String

studentTable.setRowFactory(tableView -> {
    final TableRow<Attendance> row = new TableRow<>();

        for (Attendance item : studentTable.getItems()) {
            if (item.getStatus().equals("present")) {
                row.setStyle("-fx-background-color:green;");
            }
            else if (item.getStatus().equals("absent")){
                row.setStyle("-fx-background-color:red;");
            }
            else {
                row.setStyle("-fx-background-color:white;");
            }
        }
return row;
    });
}

PICTURE WITH RESULT: Image

I will be thankful for any solution and any help :)


Solution

  • All your code does is create a TableRow when needed, and then each time a TableRow is created, it iterates over all the items in the table, continually changing the style of that one single row. So the row will simply have the style determined by the last item in the table's items list (because that item determines the final call to setStyle(...)). And of course, you do this for every row you create, so unsurprisingly every row has the same style.

    The TableRow's updateItem(...) method is called when the row is first used to display an Attendance instance, and again any time the row is reused to display a different Attendance instance. Thus you need to override updateItem() and place the logic there.

    studentTable.setRowFactory(tableView -> new TableRow<Attendance>() {
        @Override
        protected void updateItem(Attendance attendance, boolean empty) {
            super.updateItem(attendance, empty);
            if (empty) {
                setStyle("");
            } else if (attendance.getStatus().equals("present")) {
                setStyle("-fx-background-color:green;");
            } else if (attendance.getStatus().equals("absent")) {
                setStyle("-fx-background-color:red;");
            } else {
                setStyle("-fx-background-color:white;");
            }
        }
    });