Reputation: 13
i am currently working on a small learning-project with a TableView Element. I am changeing the background colors of each row according to its content like that:
TableView.setRowFactory((row) -> new TableRow<Person>() {
@Override
public void updateItem(Person person, boolean empty) {
super.updateItem(person, empty);
switch (person.getPersonStatus()) {
case ST:
setStyle("-fx-control-inner-background: " + StatusColor.B_LIGHT.getMyColorValue() + "; -fx-text-fill: #fff;");
break;
case CD:
setStyle("-fx-control-inner-background: " + StatusColor.D_LIGHT.getMyColorValue() + "; -fx-text-fill: #fff;");
break;
}
}
i additionally like to get a reference of the object in that row when i doubleclick on the row. I use this code for that:
TableView.setRowFactory((row) -> {
TableRow<Person> row = new TableRow<>();
row.setOnMouseClicked(event -> {
if (event.getClickCount() == 2 && (!row.isEmpty())) {
Person rowData = row.getItem();
System.out.println(rowData);
}
});
return row;
});
but that doesn't work together (i assume because i am assigning two factorys which override each other). Can somebody please help me out to combine both code examples into a working one? How is it possible to override a function (updateItem) in a factory and attach a listener at the same time?
best regards
Upvotes: 1
Views: 692
Reputation: 209684
Just add the listener to the TableRow
you create in the first code block:
TableView.setRowFactory((tv) -> {
TableRow<Row> row = new TableRow<Person>() {
@Override
public void updateItem(Person person, boolean empty) {
super.updateItem(person, empty);
switch (person.getPersonStatus()) {
case ST:
setStyle("-fx-control-inner-background: " + StatusColor.B_LIGHT.getMyColorValue() + "; -fx-text-fill: #fff;");
break;
case CD:
setStyle("-fx-control-inner-background: " + StatusColor.D_LIGHT.getMyColorValue() + "; -fx-text-fill: #fff;");
break;
}
}
};
row.setOnMouseClicked(event -> {
if (event.getClickCount() == 2 && (!row.isEmpty())) {
Person rowData = row.getItem();
System.out.println(rowData);
}
});
return row;
});
Upvotes: 1