java 对 jTable 中的一列求和?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27129623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:17:37  来源:igfitidea点击:

Sum a Column in a jTable?

javaswingjtable

提问by BEE

I am having a problem trying to get values from a column within a jTable and sum them up. This is the code I have so far:

我在尝试从 jTable 中的列中获取值并对它们求和时遇到问题。这是我到目前为止的代码:

public void saveTable(){
    for(int i = 0; i < jTable2.getRowCount(); i++){
        int total = 0;
        int Amount = (int) jTable2.getValueAt(i, 5);
        total = Amount+total;
        System.out.println(total);
    }
}

However I keep getting ClassCastException Errors specifically:

但是我不断收到 ClassCastException 错误:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:      java.lang.String cannot be cast to java.lang.Integer
at my.rcsv1.accounting.DraftInvoice.saveTable(DraftInvoice.java:851)

Which is referring to the line of code:

这是指代码行:

int Amount = (int) jTable2.getValueAt(i, 5);

What do I need to do in order to get this to work?

我需要做什么才能让它发挥作用?

Thank you!

谢谢!

采纳答案by Daniel Kec

int Amount = Integer.parseInt(jTable2.getValueAt(i, 5)+"");

Will do the thing

会做事

回答by Liam de Haas

You are casting to a primitive data type, you should be parsing.

您正在转换为原始数据类型,您应该进行解析。

Try this:

试试这个:

int amount = Integer.parseInt(jTable2.getValueAt(i, 5));

int amount = Integer.parseInt(jTable2.getValueAt(i, 5));

Also you shouldn't start variable names with a capital ie int Amountshould be int amount

另外你不应该用大写的变量名开始,即int Amount应该是int amount

回答by Joop Eggen

The exception says you stored a String in that column.

异常表示您在该列中存储了一个字符串。

You might do in better style by using the data model, jTable.getModel(). But this is it:

通过使用数据模型,您可能会做得更好jTable.getModel()。但就是这样:

    int total = 0;
    for (int i = 0; i < jTable2.getRowCount(); i++){
        int amount = Integer.parseInt((String) jTable2.getValueAt(i, 5));
        total += amount;
    }
    System.out.println(total);