TableView 列数据设置为 2 位小数 [英] TableView column data set to 2 decimal places
问题描述
我有 1 个类文件 Nepokretnost.java,其中的构造函数如下所示:
I have 1 class file Nepokretnost.java in which constructor look like this:
public Nepokretnost(String tipNepokretnosti, String zona, String pravo,
double povrsina, int amortizacija, double osnovica, double kredit, double porez) {
this.tipNepokretnosti = tipNepokretnosti;
this.zona = zona;
this.pravo = pravo;
this.povrsina = povrsina;
this.amortizacija = amortizacija;
this.osnovica = osnovica;
this.kredit = kredit;
this.porez = porez;
}
此外,我有每个类字段的列的 TableView.我的问题是双字段povrsina".我想从 TextField 设置它.
Further, I have TableView with column for each of class fields. My problem is double field "povrsina". I want to set it from TextField.
我将名为 txtPovrsina 的 TextField 内容发送到双变量:
I sent contents of TextField named txtPovrsina to double variable:
double dPovrsina;
dPovrsina = Double.parseDouble(txtPovrsina.getText());
然后将所有字段放入TableView:
then put all fields in TableView:
ObservableList<Nepokretnost> data = tblTabela.getItems();
data.add(new Nepokretnost(cboNepokretnost.getValue().toString(),cboZona.getValue().toString(),
txtPravo,dPovrsina,40,450000.25,2500.00,2500.00));
一切正常,但我想要一些应用程序的行为,我不知道如何设置.现在,当我将像 25 这样的 int 放入 TextField 时,我在 TableView 列中得到 25.0.我希望所有列单元格都恰好有 2 个小数位.
All is working well, but I want some behavior of app I can't figure out how to set. Right now when I put int like 25 in TextField I get 25.0 in TableView column. I want all column cells to have exactly 2 decimal places.
我试过了:
DecimalFormat df=new DecimalFormat("#.00");
ObservableList<Nepokretnost> data = tblTabela.getItems();
data.add(new Nepokretnost(cboNepokretnost.getValue().toString(),cboZona.getValue().toString(),
txtPravo,df.format(dPovrsina),40,450000.25,2500.00,2500.00));
但我收到错误不兼容的类型:字符串无法转换为双精度"
but I get error "Incompatible types: String cannot be converted to double"
我仍然是 Java 中的菜鸟,但我的猜测是格式正在制作字符串,我想输入保持双精度只是为了有 2 个小数位.像本专栏一样,其他双字段也会有同样的问题.
I am still noob in java but my guess is format is making String and I want to input stay double just to have 2 decimal places. Like this column I will have same issue with other double fields.
谁能给我一些指导?
推荐答案
您希望更改数据在表格中的显示方式,而不是更改数据本身.为此,您需要在表格列上设置一个单元工厂.类似的东西
You want to change the way the data is displayed in your table, not change the data itself. To do that, you need to set a cell factory on your table column. Something like
TableView<Nepokretnost> table = new TableView<>();
TableColumn<Nepokretnost, Number> povrsinaCol = new TableColumn<>("Povrsina");
povrsinaCol.setCellValueFactory(cellData ->
new ReadOnlyDoubleWrapper(cellData.getValue().getPovrsina()));
povrsinaCol.setCellFactory(tc -> new TableCell<Nepokretnost, Number>() {
@Override
protected void updateItem(Number value, boolean empty) {
super.updateItem(value, empty) ;
if (empty) {
setText(null);
} else {
setText(String.format("%0.2f", value.doubleValue()));
}
}
});
这篇关于TableView 列数据设置为 2 位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!