So I have done some digging around on the JavaFx TableView and I have found some nice solutions to simple situations.
This article provides a nice explanation of how to
I assumed that the size (# of Entries) of each Map does not change during runtime, or better: there is a fixed maximum of entries. If this is the case, the TableView
can access each Entry
the same way as it does with standard attributes (or a Property
).
Here is a modified class of Person
.
public class PersonSimple {
String firstName;
String lastName;
String age;
Map map;
public PersonSimple(String fn, String ln, String age, Double gr0, Double gr1, Double gr2)
{
this.firstName = fn;
this.lastName = ln;
this.age = age;
map = new LinkedHashMap<>();
map.put(0, gr0);
map.put(1, gr1);
map.put(2, gr2);
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return firstName;
}
public String getAge()
{
return age;
}
private Double getFromMap(Integer key)
{
Set> s = map.entrySet();
Iterator> iter = s.iterator();
int index = 0;
while(iter.hasNext())
{
Entry e = iter.next();
if(index == key.intValue())
{
return e.getValue();
}
index++;
}
return null;
}
public Double getFM0()
{
return getFromMap(0);
}
public Double getFM1()
{
return getFromMap(1);
}
public Double getFM2()
{
return getFromMap(2);
}
}
As you can see, every PersonSimple
has a Map
which must hold three entries. Now comes the trick. For each of these entries you have define a get-method. Be careful how you name them, because this part is crucial to the interaction with the TableView
.
The following code shows how you connect these new methods to the TableView
.
TableColumn firstNameCol = new TableColumn("First Name");
TableColumn lastNameCol = new TableColumn("Last Name");
TableColumn ageCol = new TableColumn("Age");
TableColumn aCol = new TableColumn("Assignment1");
TableColumn bCol = new TableColumn("Assignment2");
TableColumn cCol = new TableColumn("Assignment3");
table.getColumns().addAll(firstNameCol, lastNameCol, ageCol,aCol,bCol,cCol);
firstNameCol.setCellValueFactory(new PropertyValueFactory("firstName"));
lastNameCol.setCellValueFactory(new PropertyValueFactory("lastName"));
ageCol.setCellValueFactory(new PropertyValueFactory("age"));
aCol.setCellValueFactory(new PropertyValueFactory("FM0"));
bCol.setCellValueFactory(new PropertyValueFactory("FM1"));
cCol.setCellValueFactory(new PropertyValueFactory("FM2"));
It is highly important that each PropertyValueFactor
gets a name that fits to one of the get-methods in the class PersonSimple
. See the TableView-API for more information about that.
Of course, my approach does not solve the problem with getting the data from dynamic maps, because as far as i know it is not possible in Java to add new methods to a class during runtime. But there might be a trick using the reflection-api to circumvent this limitation.