JavaFx use String with Double on table column

2019-01-20 14:47发布

问题:

I have a class called "Product", with a double attribute "price". I'm showing it on a table column inside a table view, but i wanted to show the price formatted -- "US$ 20.00" instead of just "20.00".

Here's my code for populating the table view:

priceProductColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty());

I tried everything: convert the returned value to a string, using the method toString that priceProperty has, etc, but not seems to work.

Do i need to bind an event of something like that?

回答1:

Use the cellValueFactory as you have it to determine the data that is displayed. The cell value factory is basically a function that takes a CellDataFeatures object and returns an ObservableValue wrapping up the value to be displayed in the table cell. You usually want to call getValue() on the CellDataFeatures object to get the value for the row, and then retrieve a property from it, exactly as you do in your posted code.

Use a cellFactory to determine how to display those data. The cellFactory is a function that takes a TableColumn (which you usually don't need) and returns a TableCell object. Typically you return a subclass of TableCell that override the updateItem() method to set the text (and sometimes the graphic) for the cell, based on the new value it is displaying. In your case you get the price as a Number, and just need to format it as you require and pass the formatted value to the cell's setText(...) method.

It's worth reading the relevant Javadocs: TableColumn.cellFactoryProperty(), and also Cell for a general discussion of cells and cell factories.

priceProductColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty());

priceProductColumn.setCellFactory(col -> 
    new TableCell<Product, Number>() {
        @Override 
        public void updateItem(Number price, boolean empty) {
            super.updateItem(price, empty);
            if (empty) {
                setText(null);
            } else {
                setText(String.format("US$%.2f", price.doubleValue()));
            }
        }
    });

(I'm assuming priceProductColumn is a TableColumn<Product, Number> and Product.priceProperty() returns a DoubleProperty.)



回答2:

If you have not, read this together with @James_D post.

https://docs.oracle.com/javafx/2/ui_controls/table-view.htm