user3119884
user3119884

Reputation: 19

Calculate the sum of a column and put it on that jtable

How can I calculate sum of price column in jTable and put sum of them at the end of the jTable. Can you give me a sample code?

public class IncomeReport extends JFrame {

private AccountFacade service = new AccountFacade();

void init() {

    String[] columnNames = {"مبلغ", "محل درآمد ", "منبع"};

    List list = service.incomeReportFacade();

    Object[][] model = new Object[list.size()][];
    for (int i = 0; i < list.size(); i++) {
        model[i] = (Object[]) list.get(i);
    }

    JTable table = new JTable(model, columnNames) {


        DefaultTableCellRenderer renderRight = new DefaultTableCellRenderer();

        {
            // initializer block
            renderRight.setHorizontalAlignment(SwingConstants.RIGHT);
        }

        @Override
        public TableCellRenderer getCellRenderer(int arg0, int arg1) {
            return renderRight;
        }

    };

Upvotes: 1

Views: 5633

Answers (2)

jzd
jzd

Reputation: 23629

If you need a total that is dynamically kept up to date then you will need to either override your TableModel to provide the sum for the final row, or will need to listener for changes to the model and update the last row with the sum.

Customizing your own TableModel would also allow you the ability to make your summary row uneditable so while this might be more work, it provides much more flexibility.

Upvotes: 0

Paul Samsotha
Paul Samsotha

Reputation: 208994

Try something like this. Get the model, and use the DefaultTableModel#getValueAt() method.

Jtable table = new Jtable();
DefaultTableModel model = (DefaultTableModel)table.getModel();

double total = 0;
int column = 2;  // example

for (int i = 0; i < model.getRowCount(); i++){
    total += model.getValueAt(i, column);        // getValueAt(row, column)
}

Object[] row = {"", "", total};
model.addRow(row);

Upvotes: 1

Related Questions