سؤال

I'm trying to add the prices of selected items and then return it to the main class where i'm gonna add them to other values. However, when i'm running the program i got very large numbers compare to what i have.

so far i got till here.

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];
          }


       }
    }

please help.

thanks.

هل كانت مفيدة؟

المحلول

Since you are using a selection mode of MULTIPLE_INTERVAL_SELECTION you have to account for all selections. Consider using a method like this to calculate the total.

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

Then you can call this from your "Calculate" button press. This approach also does not require that you implement ListSelectionListener and you can remove your valueChanged method.

نصائح أخرى

A ListSelectionListener fires multiple events because you need to unselect one row and then select another row. So you probably don't want to calculate your total every time the selection changes.

Instead you probably need a "Calculate Total" button. Then when that button is click you use the JList API to get all the selected items and then calculate the total.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top