2015-04-15 56 views
0

把單獨的值我似乎無法找到這個新到Java/JavaFX的一個解決方案:的JavaFX的TableView:在特定的列

我有一個3列的tableview,最後一列是價格列。 無論何時從tableview中添加或刪除一行,我都想要顯示價格列的運行總數。

TableView從ObservableList中填充,它每行包含3個字段對象。 String id,String product,Double price .........這是我想在單獨的textField中保持總計的價格

回答

1

由於tableview的項目是ObservableList,因此您可以跟蹤對於ListChangeListener,並更新計算出的總價格:

public class Sample extends Application 
{ 

    @Override 
    public void start(Stage primaryStage) 
    { 
     // items set to tableview 
     ObservableList<Product> products = FXCollections.observableArrayList(); 

     DoubleProperty totalProperty = new SimpleDoubleProperty(0); 

     products.addListener((ListChangeListener.Change<? extends Product> change) -> 
     { 
      while (change.next()) 
      { 
       if (change.wasAdded()) 
       { 
        for (Product p : change.getAddedSubList()) 
        { 
         totalProperty.set(totalProperty.get() + p.getPrice()); 
        } 
       } 
       else if (change.wasRemoved()) 
       { 
        for (Product p : change.getRemoved()) 
        { 
         totalProperty.set(totalProperty.get() - p.getPrice()); 
        } 
       } 
      } 
     }); 

     TextField textField = new TextField(); 
     textField.textProperty().bind(totalProperty.asString()); 

     Random random = new Random(); 

     Button btnAdd = new Button("Add product"); 
     btnAdd.setOnAction((ActionEvent event) -> 
     { 
      products.add(new Product("new", (double) random.nextInt(100))); 
     }); 

     Button btnRemove = new Button("Remove product"); 
     btnRemove.setOnAction((ActionEvent event) -> 
     { 
      if (products.size() > 0) 
      { 
       products.remove(random.nextInt(products.size())); 
      } 
     }); 

     VBox root = new VBox(); 
     root.getChildren().addAll(textField, btnAdd, btnRemove); 

     Scene scene = new Scene(root, 300, 250); 

     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 


    public static class Product 
    { 
     String name; 
     Double price; 


     public Product(String name, Double price) 
     { 
      this.name = name; 
      this.price = price; 
     } 


     public String getName() 
     { 
      return name; 
     } 


     public void setName(String name) 
     { 
      this.name = name; 
     } 


     public Double getPrice() 
     { 
      return price; 
     } 


     public void setPrice(Double price) 
     { 
      this.price = price; 
     } 

    } 


    public static void main(String[] args) 
    { 
     launch(args); 
    } 

}