在jTable中汇总一列?

我在尝试从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); } } 

但是我一直特别得到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) 

这是指代码行:

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

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

谢谢!

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

会做的事情

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

尝试这个:

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

此外,您不应该使用大写启动变量名称,即int Amount应该是int amount

例外情况表明您在该列中存储了一个String。

您可以使用数据模型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);