[英]getting sum of jtable values continuously
I want to get the sum of all the values from jtable continuously. 我想连续从jtable获取所有值的总和。 Like I have made a jtable where the user will put data continuously and whenever a new row will insert in the jtable then some code should execute for taking all the sum of values of jtable and then set it on a text filed.
就像我制作了一个jtable一样,用户将连续放置数据,并且每当在jtable中插入新行时,都应执行一些代码以获取jtable的所有值的总和,然后将其设置在文本字段上。 I have written the code but I don't that in which event I should use the code so that when a new row is inserted in the table then the code runs and get the new sum of all values and store in a text field.
我已经编写了代码,但是我没有在那种情况下使用代码,以便当在表中插入新行时,代码将运行并获取所有值的新总和并存储在文本字段中。 So now in which method of jtable I should use this code so when a new row is inserted so that code executes.
因此,现在应该在哪种jtable方法中使用此代码,以便在插入新行时执行代码。 The code is here...
代码在这里...
int rows=productionTable.getRowCount();
int totalBundles=0;
int totalBoxes=0;
//totalBundles
for(int i=0;i<rows;i++)
{
totalBundles=totalBundles+Integer.parseInt(productionTable.getValueAt(i, 1)+"");
}
this.totalBundlesTextField.setText(totalBundles+"");
//
//totalBoxes
for(int i=0;i<rows;i++)
{
totalBoxes=totalBoxes+Integer.parseInt(productionTable.getValueAt(i, 2)+"");
}
this.totalBoxesTextField.setText(totalBoxes+"");
//
So now in which method of jtable I should use this code so when a new row is inserted so that code execute
因此,现在应该在哪种jtable方法中使用此代码,以便在插入新行时执行代码
You do this when the data in the TableModel
changes. 当
TableModel
的数据更改时,您可以执行此操作。 So you can add a TableModelListener
to the TableModel
of your table. 因此,您可以将
TableModelListener
添加到表的TableModel
中。 Then a TableModelEvent
will be generated when you: 然后,当您执行以下操作时,将生成
TableModelEvent
:
In each of the above cases you could then iterate through the TableModel
to calculate the new value. 在上述每种情况下,您都可以遍历
TableModel
来计算新值。
Check out JTable -> TableModeListener for a simple example of use a TableModelListener
. 查看JTable-> TableModeListener以获得使用
TableModelListener
的简单示例。
The above approach assumes that you don't have a lot a data in your model, since it recalculates the value each time a change is made. 上面的方法假定您的模型中没有太多数据,因为每次更改时它都会重新计算值。
If you have a lot of data this is not very efficient so you may want to keep a running total of the value in your TableModel. 如果您有很多数据,这不是很有效,那么您可能希望将TableModel中的值保持连续运行。 So you would need to customize the TableModel to keep a total.
因此,您需要自定义TableModel以保留总数。 And then in methods like setValueAt(...), insertRow(...), removeRow(...) you would need to add logic to update the total as the model is updated.
然后在setValueAt(...),insertRow(...),removeRow(...)之类的方法中,您需要添加逻辑以在更新模型时更新总数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.