TableView列数据设置为小数点后2位

TableView column data set to 2 decimal places

我有 1 个 class 文件 Nepokretnost.java,其中构造函数如下所示:

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,每个 class 字段都有列。我的问题是双字段 "povrsina"。我想从 TextField 中设置它。

我将名为 txtPovrsina 的文本字段的内容发送到双变量:

double dPovrsina;
dPovrsina = Double.parseDouble(txtPovrsina.getText());

然后将所有字段放入 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));

一切正常,但我想要一些我不知道如何设置的应用程序行为。现在,当我在 TextField 中输入 25 之类的 int 时,我在 TableView 列中得到 25.0。我希望所有列单元格都正好有 2 位小数。

我试过了:

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));

但我收到错误 "Incompatible types: String cannot be converted to double"

我在 java 中仍然是菜鸟,但我的猜测是格式正在生成字符串,我想输入保持双精度,只是为了有 2 个小数位。像本专栏一样,我将遇到与其他双字段相同的问题。

谁能给我一些指导?

您想更改数据在 table 中的显示方式,而不是更改数据本身。为此,您需要在 table 列上设置一个细胞工厂。像

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<Nepokretnost> table = new TableView<>();
TableColumn<Nepokretnost, Number> povrsinaCol = new TableColumn<>("Povrsina");
povrsinaCol.setCellValueFactory(cellData -> 
    new ReadOnlyDoubleWrapper(cellData.getValue().getPovrsina().asObject()));

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()));
        }
    }
});