javafx - Tableview row style -
i have tableview want apply depend on value of row item diferent styles.
for example:
each row represents person property years, if person < 18 years, row color should red. if person > 60 years, row color should greeen...
i search on apply style rows, cases try apply selected rows , others use cellfactories (i don't know if possible style whole row or need apply style each field).
just set row factory. best way manage styles use css pseudoclass
s. in example have 1 "young" , 1 "old":
psuedoclass old = pseudoclass.getpseudoclass("old"); psuedoclass young = pseudoclass.getpseudoclass("young"); tableview.setrowfactory(tv -> { tablerow<person> row = new tablerow<>(); changelistener<number> yearslistener = (obs, oldage, newage) -> { int age = newage.intvalue(); row.pseudoclassstatechanged(old, age > 60); row.pseudoclassstatechanged(young, age < 18); }; row.itemproperty().addlistener((obs, previousperson, currentperson) -> { if (previousperson != null) { previousperson.yearsproperty().removelistener(yearslistener); } if (currentperson != null) { currentperson.yearsproperty().addlistener(yearslistener); row.pseudoclassstatechanged(old, currentperson.getyears() > 60); row.pseudoclassstatechanged(young, currentperson.getyears() < 18); } else { row.pseudoclassstatechanged(old, false); row.pseudoclassstatechanged(young, false); } }); return row ; });
if know years fixed each person
(i.e. won't change while table displayed), can simplify to
psuedoclass old = pseudoclass.getpseudoclass("old"); psuedoclass young = pseudoclass.getpseudoclass("young"); tableview.setrowfactory(tv -> { tablerow<person> row = new tablerow<>(); row.itemproperty().addlistener((obs, previousperson, currentperson) -> { if (currentperson != null) { row.pseudoclassstatechanged(old, currentperson.getyears() > 60); row.pseudoclassstatechanged(young, currentperson.getyears() < 18); } else { row.pseudoclassstatechanged(old, false); row.pseudoclassstatechanged(young, false); } }); return row ; });
now apply style create external style sheet styles want:
.table-row-cell:young { -fx-background: green ; } .table-row-cell:old { -fx-background: blue ; }
Comments
Post a Comment