[英]Sum a Column in a 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
异常表示您在该列中存储了一个字符串。
通过使用数据模型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);
通过构造函数调用方法
public moneyManager() {
initComponents();
getSum();
table_update();//table gets updated when records added
getSum();
}
方法实现
private void getSum() {
int sum = 0;
for(int i =0;i<jTable1.getRowCount();i++){
sum = sum +Integer.parseInt(jTable1.getValueAt(i, 2).toString());
//here i is the row wise iteration and 2 is the column number of my
calculation attribute
}
//JlableTotal is where I want to display the total
JlableTotal.setText(Integer.toString(sum));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.