is there any chance to code TableView row color on selected row? I mean something like that: I have for example TableView filled with movies and I want a specific movie (row) to change color on click to - green when it is in shop - or - to red - when it is not in shop. We will know if it is in shop or not by making simple function with query to database, but I also need some function which will be able to change selected row background color. Is there any way to make with code something like that?
Asked
Active
Viewed 732 times
0
-
https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TableCell.html – Mordechai Nov 21 '16 at 19:26
1 Answers
2
You can do something along the lines of:
TableView<Movie> table = ... ;
PseudoClass outOfStockPseudoClass = PseudoClass.getPseudoClass("out-of-stock");
table.setRowFactory(tv -> {
TableRow<Movie> row = new TableRow<>();
row.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
if (isNowSelected) {
boolean outOfStock = checkIfOutOfStock(row.getItem()) ;
row.pseudoClassStateChanged(outOfStockPseudoClass, outOfStock);
}
});
row.itemProperty().addListener((obs, oldMovie, newMovie) -> {
if (row.isSelected()) {
boolean outOfStock = checkIfOutOfStock(newMovie) ;
row.pseudoClassStateChanged(outOfStockPseudoClass, outOfStock);
}
});
return row ;
});
And then in your external CSS file do
.table-row-cell {
-fx-selection-bar: /* color for in-stock selected row */ ;
}
.table-row-cell:out-of-stock {
-fx-selection-bar: /* color for out-of-stock selected row */;
}
If you can check whether the movie is in stock at the time you initialize the data from the database, you can simplify your row factory:
table.setRowFactory(tv -> new TableRow<Movie>() {
@Override
protected void updateItem(Movie item, boolean empty) {
super.updateItem(item, empty);
pseudoClassStateChanged(outOfStockPseudoClass,
item!=null && item.isOutOfStock());
}
});

James_D
- 201,275
- 16
- 291
- 322
-
hmm this might work but color is not chaning : / external CSS file is standard application.css ? do I have to link it to application to work or something? I mean, can i somehow do it without pseudoClass, like here: http://stackoverflow.com/questions/30889732/javafx-tableview-change-row-color-based-on-column-value and yes, on tableview initialization or refresh I wont make query check if that movie is in stock or not? – Damian Szarik Paul Nov 24 '16 at 21:28