gpt4 book ai didi

JavaFX 使 cellFactory 通用

转载 作者:行者123 更新时间:2023-11-29 04:29:19 26 4
gpt4 key购买 nike

我正在尝试编写一种方法,允许我为作为参数传递的特定列设置列工厂。在这种情况下,我有订单和食品,这两个类在某个时候都显示在 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);
}
}

最佳答案

有一个小错字对您的代码产生了巨大影响。你用过

protected void updateItem(double item, boolean empty)

代替

protected void updateItem(Double item, boolean empty)

由于您使用原始类型 double 而不是也用作类型参数的 Double 类型,因此您不会覆盖 updateItem方法,而是创建一个新方法。从未使用过此方法。而是使用默认的 updateItem 方法。此实现不会修改单元格的文本。

提示:始终在覆盖方法时使用@Override 注释。这允许编译器检查这样的错误。此外,您还应该在 priceCellFormatting 方法中为方法参数添加类型参数:

public static <T> void priceCellFormatting(TableColumn<T, Double> tableColumn){
System.out.println();

tableColumn.setCellFactory(col ->
new TableCell<T, Double>() {

@Override
protected void updateItem(Double item, boolean empty) {
super.updateItem(item, empty);
if(empty){
setText(null);
}else {
setText(String.format("%.2f €", item));
}


}
});

}

关于JavaFX 使 cellFactory 通用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44470411/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com