【发布时间】:2017-06-10 06:40:50
【问题描述】:
我正在尝试编写一种方法,该方法允许我为作为参数传递的特定列设置列工厂。在这种情况下,我有 Orders 和 Food,这两个类在某个时间点都显示在 TableView 中,并且都有一个我想格式化为价格的列。
这就是它的工作原理:
priceColumn.setCellFactory(col ->
new TableCell<Food, Double>() {
@Override
public void updateItem(Double price, boolean empty) {
super.updateItem(price, empty);
if (empty) {
setText(null);
} else {
setText(String.format("%.2f €", price));
}
}
}
);
这是我的 Formatting 类,我在其中尝试使其通用,而不是为每一列复制粘贴相同的东西。问题是它什么都不会显示。
public static <T> void priceCellFormatting(TableColumn tableColumn){
System.out.println();
tableColumn.setCellFactory(col ->
new TableCell<T, Double>() {
protected void updateItem(double item, boolean empty) {
super.updateItem(item, empty);
if(empty){
setText(null);
}else {
setText(String.format("%.2f €", item));
}
}
});
}
我调用这个方法,除了价格之外的每一列都被填满:
private void fillTableListView() {
nameColumn.setCellValueFactory(new PropertyValueFactory<Order, String>("name"));
amountColumn.setCellValueFactory(new PropertyValueFactory<Order, Integer>("amount"));
priceColumn.setCellValueFactory(new PropertyValueFactory<Order, Double>("price"));
totalColumn.setCellValueFactory(new PropertyValueFactory<Order, Double>("total"));
Formatting.priceCellFormatting(priceColumn);
try {
orderTableView.setItems(OrderDAO.getOrder());
} catch (SQLException e) {
System.out.println("Exception at filling tablelistview: " + e);
}
}
【问题讨论】:
-
你需要一个 cellValueFactory。见stackoverflow.com/questions/44443305/…
-
在调用此方法之前我已经这样做了。 priceColumn.setCellValueFactory(new PropertyValueFactory
("price"));