JavaFx - show objects in TableView containing ObservableList -
i have class person
amongst other attributes contains observablelist<car>
. want display data in tableview
looks this:
first name | last name | car -----------+-----------+--------- john | doe | bmw john | doe | audi walter | johnson | chrysler
how can javafx extract list of class person
, create row each item in list?
the easyest way create new class carofperson, contains car , owner:
class carofperson { person myowner; car mycar; public carofperson(car car, person person) { myowner = person; mycar = car; } public person getowner() { return myowner; } public car getcar() { return mycar; } }
this class can used table item. if create observable list these instances set table as:
tablecolumn<carofperson,string> c1 = new tablecolumn<carofperson,string>("first"); c1.setcellvaluefactory(p -> p.getvalue().getowner().firstnameproperty()); table.getcolumns().add(c1); tablecolumn<carofperson,string> c2 = new tablecolumn<carofperson,string>("last"); c2.setcellvaluefactory(p -> p.getvalue().getowner().lastnameproperty()); table.getcolumns().add(c2); tablecolumn<carofperson,string> c3 = new tablecolumn<carofperson,string>("car"); c3.setcellvaluefactory(p -> p.getvalue().getcar().typeproperty()); table.getcolumns().add(c3);
the main challenge either:
- create list of carofperson out of persons, drawback required build potentially huge list of separate instances, difficult keep in sync list of persons if changes made.
create view of type observablelist dynamically creates carofperson objects on demand:
observablelist<carofperson> list = new observablelistbase<carofperson>(){ observablelist<person> mypersons = persons; boolean observed = false; @override public carofperson get(int index) { system.out.println("get "+index); (person person : mypersons) { if (person.getnumberofcars() > index) return new carofperson(person.getcar(index), person); index -= person.getnumberofcars(); } return new carofperson(new car("null"), new person("n", "n")); } @override public int size() { if (!observed) { mypersons.addlistener((listchangelistener.change<? extends tableinvbox.person> c) -> { beginchange(); nextadd(0, integer.max_value); endchange(); }); observed = true; } int size = 0; (person person : mypersons) size += person.getnumberofcars(); return size; } };
this act potentiall huge list of observable carofpersons. each of these instances generated on demand , if shown in current table ....
the observation of mypersons update tableview show changes in persons list. adding, removing persons or names reflected in table.
of course implementation if inefficient, iterating through persons proper index, optimized. ment hint.
Comments
Post a Comment