我正在使用数据库中的一些数据创建一个 TableView 。为了使数据信息更丰富,我想为其添加后缀,例如价格后的“,-”(整数)等。
现在,字符串连接可以很好地添加此后缀(我的列采用通用数据类型),但随后 TableView 中的内置排序机制将开始将列排序为字符串而不是整数(或其他数据类型)。那么,有没有一种方法可以将整数值(或与此相关的任何数据类型)的后缀添加到表列,同时仍然保持排序机制完好无损?
在来这里之前我在网上进行了搜索,遗憾的是没有任何运气。
最佳答案
通常,您使用为列实现Comparable
(如Integer
)的值类型,并使用cellFactory
来修改值的方式显示:
public static class Item {
private BigDecimal price;
public BigDecimal getPrice() {
return price;
}
public Item(BigDecimal price) {
this.price = price;
}
}
@Override
public void start(Stage primaryStage) {
TableView<Item> table = new TableView<>();
TableColumn<Item, BigDecimal> column = new TableColumn<>();
column.setCellValueFactory(new PropertyValueFactory<>("price"));
column.setCellFactory(new Callback<TableColumn<Item, BigDecimal>, TableCell<Item, BigDecimal>>() {
private final Font font = Font.font("monospaced");
private final BigDecimal hundred = BigDecimal.valueOf(100);
private final char decimalSeparator = DecimalFormatSymbols.getInstance().getDecimalSeparator();
@Override
public TableCell<Item, BigDecimal> call(TableColumn<Item, BigDecimal> param) {
return new TableCell<Item, BigDecimal>() {
{
setAlignment(Pos.BASELINE_RIGHT);
setFont(font);
}
@Override
protected void updateItem(BigDecimal item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText("");
} else {
BigInteger num = item.toBigInteger();
int frac = item.movePointRight(2).abs().remainder(hundred).intValue();
String numPart = String.format("%,d", num) + decimalSeparator;
setText(numPart + (frac == 0 ? "- " : String.format("%02d", frac)));
}
}
};
}
});
table.getColumns().add(column);
table.getItems().addAll(
new Item(new BigDecimal("2")),
new Item(new BigDecimal("2.5")),
new Item(new BigDecimal("5555.99")),
new Item(new BigDecimal("123456789.77")),
new Item(new BigDecimal("22011.05")),
new Item(new BigDecimal("4211"))
);
Scene scene = new Scene(table);
primaryStage.setScene(scene);
primaryStage.show();
}
(您还可以使用自定义 Comparator
作为 comparator
property of TableColumn
的值来指定值的排序方式;这可用于将 -
视为 0
并忽略任何组分隔符(如有必要)。)
关于JavaFX:向 TableView 数据添加后缀并保持正确的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43304937/