我有ObservableList
类GameLogEntry
的实例:
public class GameLogEntry {
private int gameNumber;
private int chosenStratA;
private int chosenStratB;
private Double[] scoresByB;
private Double[] scoresByA;
private double higherPrice;
private double lowerPrice;
private double averagePrice;
private int maxIndex;
在我的程序中,我使用此ObservableList中的值填充TableView的列。
我的专栏:
@FXML
private TableColumn<GameLogEntry, String> colGameNum;
@FXML
private TableColumn<GameLogEntry, String> colChosenStratA;
@FXML
private TableColumn<GameLogEntry, String> colScoreByBOne;
@FXML
private TableColumn<GameLogEntry, String> colScoreByBTwo;
@FXML
private TableColumn<GameLogEntry, String> colChosenStratB;
@FXML
private TableColumn<GameLogEntry, String> colScoreByAOne;
@FXML
private TableColumn<GameLogEntry, String> colScoreByATwo;
@FXML
private TableColumn<GameLogEntry, String> colLowerPrice;
@FXML
private TableColumn<GameLogEntry, String> colHigherPrice;
@FXML
private TableColumn<GameLogEntry, String> colAveragePrice;
我正在initialize
方法中这样做:
colGameNum.setCellValueFactory(new PropertyValueFactory<GameLogEntry, String>("gameNumber"));
colChosenStratA.setCellValueFactory(new PropertyValueFactory<GameLogEntry, String>("chosenStratA"));
colChosenStratB.setCellValueFactory(new PropertyValueFactory<GameLogEntry, String>("chosenStratB"));
colHigherPrice.setCellValueFactory(new PropertyValueFactory<GameLogEntry, String>("higherPrice"));
colLowerPrice.setCellValueFactory(new PropertyValueFactory<GameLogEntry, String>("lowerPrice"));
colAveragePrice.setCellValueFactory(new PropertyValueFactory<GameLogEntry, String>("averagePrice"));
但是我还需要填充CS(B1),CS(B2),CS(A1)和CS(A2)列。
CS(B1)应该用scoresByB [0],
填充CS(B2)-具有scoresByB [1],
CS(A1)-具有scoresByA [0],
CS(A2)-具有scoresByA [1]。
问题是-我可以使用与其他值相同的简单方法来做到这一点吗?如果没有,我该如何以其他方式呢?
答案 0 :(得分:2)
只需自己实施工厂。您可以创建一个辅助方法来避免重复代码:
static <S, T> Callback<TableColumn.CellDataFeatures<S, T>, ObservableValue<T>> createArrayValueFactory(Function<S, T[]> arrayExtractor, final int index) {
if (index < 0) {
return cd -> null;
}
return cd -> {
T[] array = arrayExtractor.apply(cd.getValue());
return array == null || array.length <= index ? null : new SimpleObjectProperty<>(array[index]);
};
}
colScoreByBOne.setCellValueFactory(createArrayValueFactory(GameLogEntry::getScoresByB, 0));
colScoreByBTwo.setCellValueFactory(createArrayValueFactory(GameLogEntry::getScoresByB, 1));
colScoreByAOne.setCellValueFactory(createArrayValueFactory(GameLogEntry::getScoresByA, 0));
colScoreByATwo.setCellValueFactory(createArrayValueFactory(GameLogEntry::getScoresByA, 1));
要使其正常工作,您需要将列的类型更改为TableColumn<GameLogEntry, Double>
。 (实际上,您应该更改列的 all 的值类型,因为没有单个属性属于String
类型;所有属性都属于{{1 }}或Double
。)