从jtable计算行的总和

时间:2017-02-10 19:22:21

标签: java swing jtable

我正在使用jtable和rs2xml.jar库

我的桌子有3栏。 id,名称,金额 我想计算金额列的总和。

这是代码:

    //showcal is my table name
       try {

            Connection conn = getConnection();

            PreparedStatement ps
                    = conn.prepareStatement("select id,name,amount from income where idate=?");
      ps.setString(1,((JTextField) inpdatechosser.getDateEditor().getUiComponent()).getText());
            rset = ps.executeQuery();
            showcal.setModel(DbUtils.resultSetToTableModel(rset));


 //sum calculation
int total = 0;

    for (int i = 0; i < showcal.getRowCount(); i++){
        int amount = Integer.parseInt( showcal.getValueAt(i, 3).toString());
        total =total+ amount;
    }

jTextField1.setText(""+Integer.toString(total));

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }

但没有任何事情发生。我得到&#34; 3&gt; = 3&#34; 那是什么意思??为什么它不起作用?

1 个答案:

答案 0 :(得分:1)

表中的行和列索引基于零。因此第3列的索引应为2,即:showcal.getValueAt(i, 2)

您获得的异常意味着列的索引应小于列数。