Reputation: 159
I'm trying to write a method that allows me to set the column factory for a specific column that is passed as a parameter. In this context I have Orders and I have Food, both classes are shown in a TableView at some point and both have a column that I want to format as a price.
This is how it works:
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));
}
}
}
);
And this is my Formatting class in which I'm trying to make this generic instead of copy pasting the same thing for every column. The problem is that it won't show anything.
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));
}
}
});
}
I call this method and every column gets filled except for the price:
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);
}
}
Upvotes: 2
Views: 640
Reputation: 82461
There is a small typo with a huge impact in your code. You used
protected void updateItem(double item, boolean empty)
instead of
protected void updateItem(Double item, boolean empty)
Since you use the primitive type double
instead of the Double
type that is also used as type parameter, you do not override the updateItem
method, but create a new one. This method is never used. Instead the default updateItem
method is used. This implementation does not modify the cell's text.
Hint: Always use the @Override
annotation when overriding methods. This allows the compiler to check for errors like this. Also you should probably also add the type parameters for the method parameter in the priceCellFormatting
method:
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));
}
}
});
}
Upvotes: 3