JavaFX TableView:在特定列中添加单个值

JavaFX TableView: adding individual values in specific column

我似乎找不到解决这个问题的新手 java/ javafx:

我有一个 3 列的表视图,最后一列是价格列。 每当从表视图中添加或删除行时,我想显示 运行 总价格列。

TableView 由 ObservableList 填充,该 ObservableList 每行包含 3 个字段对象。 String id,String product, Double price.......这是我想在单独的 textField

中保留总计 运行 的价格

由于tableview的item是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 );
    }

}