我假设每个 Map 的大小(条目数)在运行时不会改变,或者更好:有一个固定的最大条目数。如果是这种情况,TableView 可以像使用标准属性(或Property)一样访问每个Entry。
这是Person的修改类。
public class PersonSimple {
String firstName;
String lastName;
String age;
Map<Integer, Double> 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<Entry<Integer, Double>> s = map.entrySet();
Iterator<Entry<Integer, Double>> iter = s.iterator();
int index = 0;
while(iter.hasNext())
{
Entry<Integer, Double> 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);
}
}
如您所见,每个PersonSimple 都有一个Map,它必须包含三个条目。现在是诀窍了。对于这些条目中的每一个,您都定义了一个 get 方法。请注意如何命名它们,因为这部分对于与TableView 的交互至关重要。
以下代码显示了如何将这些新方法连接到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<Person,String>("firstName"));
lastNameCol.setCellValueFactory(new PropertyValueFactory<Person,String>("lastName"));
ageCol.setCellValueFactory(new PropertyValueFactory<Person,String>("age"));
aCol.setCellValueFactory(new PropertyValueFactory<Person,Double>("FM0"));
bCol.setCellValueFactory(new PropertyValueFactory<Person,Double>("FM1"));
cCol.setCellValueFactory(new PropertyValueFactory<Person,Double>("FM2"));
非常重要的是,每个PropertyValueFactor 都有一个适合PersonSimple 类中的一种get 方法的名称。有关更多信息,请参阅the TableView-API。
当然,我的方法并不能解决从动态映射中获取数据的问题,因为据我所知,在 Java 中不可能在运行时向类添加新方法。但是可能有一个使用反射 API 的技巧来规避这个限制。