2

How can I add the data of one column of the TableView, in other of the same table but doing x operation (like add 5)?

In my case I want to add to the outTaxColumn the data of the inTaxColumn * 0.79.

Here is the controller

//Imports

public class ControladorView implements Initializable {

    @FXML private TableView tableViewBudget;
    @FXML private TableColumn<Product, String> nameBudgetColumn;
    @FXML private TableColumn<Product, Double> outTaxColumn;
    @FXML private TableColumn<Product, Double> inTaxColumn;
    @FXML private TableColumn<Product, Integer> quantityColumn;

    private ObservableList<Product> budgetData;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        //Budget Table
        nameBudgetColumn.setCellValueFactory(
            new PropertyValueFactory<>("description"));
        inTaxColumn.setCellValueFactory(
            new PropertyValueFactory<>("price"));

        budgetData = FXCollections.observableArrayList();
        tableViewBudget.setItems(budgetData);
}

Product class:

public class Product {
    public enum Category {
        SPEAKER, HDD, HDD_SSD, POWER_SUPPLY, DVD_WRITER, RAM, SCREEN,
        MULTIREADER, MOTHERBOARD, CPU, MOUSE, GPU, KEYBOARD, CASE, FAN
    }

    public Product(String description, double price, int stock, Category category) {
        this.description = description;
        this.price = price;
        this.stock = stock;
        this.category = category;
    }

    public Category getCategory() {
        return category;
    }

    public String getDescription() {
        return description;
    }

    public double getPrice() {
        return price;
    }

    public int getStock() {
        return stock;
    }

    private final String description;
    private final double price;
    private final int stock;
    private final Category category;
}
Marco Canora
  • 335
  • 2
  • 15

1 Answers1

2

You can do

outTaxColumn.setCellValueFactory(cellData ->
    new SimpleDoubleProperty(cellData.getValue().getPrice() * 0.79 ).asObject());
James_D
  • 201,275
  • 16
  • 291
  • 322
  • Can you explain how works the code? Because I don't understand how knows the lambda expression from which TableColumn has to take the values. – Marco Canora Mar 28 '16 at 11:16
  • 1
    The cell value factory maps the object for the row to an observable value to be displayed in the cell. `cellData.getValue()` gives you the object (the `Product`) for the row. `cellData.getValue().getPrice()` gives you the price for that `Product`, then multiply by 0.79. Since you declared the column as a `TableColumn` you need and `ObservableValue`: wrapping the value in a `SimpleDoubleProperty` gives you an `ObservableValue` and [`asObject()`](http://docs.oracle.com/javase/8/javafx/api/javafx/beans/property/DoubleProperty.html#asObject--) give the right type. – James_D Mar 28 '16 at 11:39