简体   繁体   English

Java,将JList中元素的值加在一起

[英]Java, Add together a value of elements in a JList

I have a jList that contains elements with 3 parameters. 我有一个jList包含具有3个参数的元素。 The elements are 元素是

Item(double code, String name, double price)

I am trying to get the total price for all elements in the list and display it in a text box. 我正在尝试获取列表中所有元素的总价并将其显示在文本框中。 Is this possible and if so, how can it be done? 这可能吗?如果可以,怎么办?

Get the ListModel from the JList 从JList获取ListModel

ListModel model = instanceOfJList.getModel();

Iterate over the model elements... 遍历模型元素...

double sum = 0;
for (int index = 0; index < model.size(); index++) {
    Item item = (Item)model.getElementAt(index);
    sum += item.getPrice();
}
// Display sum somewhere on the screen...

好吧,您可能必须遍历列表,并在每个元素上调用类似getPrice()的方法来创建总和。

Does your item class has getters for the price? 您的商品类别是否有价格的吸气剂?

If yes you can iterate over your list and each time get the price and add it to a variable; 如果是,则可以遍历列表,每次获取价格并将其添加到变量中; call it totalSum. 称之为totalSum。

At the end you should be able to display your totalSum in a text box. 最后,您应该能够在文本框中显示totalSum。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM