繁体   English   中英

添加多选JList的值

[英]adding values of multiple selection JList

我正在尝试添加所选商品的价格,然后将其返回到主类,在其中我要将其添加到其他值。 但是,当我运行该程序时,与我所拥有的相比,我得到了很多。

到目前为止,我到了这里。

import java.util.Random;
import javax.swing.*;
import java.util.Arrays;
import java.text.DecimalFormat;
import javax.swing.event.*;
import java.awt.event.*;        
import java.awt.*;

    public class OtherPrdctPanel extends JPanel implements ListSelectionListener
    {
       private JPanel otherPrdctPanel;
       private JList otherPrdctList;
       public int selectedOtherService;

       private String[] miscellaneousProd = {"Grip tape: $10",
                                             "Bearings: $30", "Riser pads: $2",
                                             "Nuts & bolts kit: $3"};
       private int[] miscellaneousProdPri = {10, 30, 2, 3};


       public OtherPrdctPanel()
       {
          setBorder(BorderFactory.createTitledBorder("Other Products"));

          otherPrdctList = new JList(miscellaneousProd);
          add(otherPrdctList);

          otherPrdctList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
          otherPrdctList.addListSelectionListener(this);

          setLayout(new GridLayout(3, 1));

       }

       public void valueChanged (ListSelectionEvent e)
       {
          int selection;
          selectedOtherService = 0;
          selection = (int)otherPrdctList.getSelectedIndex();

          for(int i = 0; i < 4; i++)
          {
             selectedOtherService = selectedOtherService + miscellaneousProdPri[selection];
          }


       }
    }

请帮忙。

谢谢。

由于您使用的是MULTIPLE_INTERVAL_SELECTION的选择模式,因此您必须考虑所有选择。 考虑使用这样的方法来计算总数。

public int calculateTotalPrice() {
    int[] selections = otherPrdctList.getSelectedIndices();
    int total = 0;
    for (int i : selections) {
        total += miscellaneousProdPri[i];
    }
    return total;
}

然后,您可以通过按“计算”按钮来调用它。 此方法也不需要实现ListSelectionListener并且可以删除valueChanged方法。

ListSelectionListener会引发多个事件,因为您需要取消选择一行,然后选择另一行。 因此,您可能不想每次选择更改时都计算总数。

相反,您可能需要一个“计算总计”按钮。 然后,当单击该按钮时,可以使用JList API获取所有选定项,然后计算总数。

暂无
暂无

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

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