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

我似乎无法找到这个和新的java / javafx的解决方案:

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

TableView从每行包含3个字段对象的ObservableList中填充。 字符串ID,字符串产品,双倍价格.........这是我想在单独的textField中保持总计的价格


由于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 );
    }

}
链接地址: http://www.djcxy.com/p/80145.html

上一篇: JavaFX TableView: adding individual values in specific column

下一篇: Duplicate columns in JavaFX TableView