0
votes

I must create a hardware shop in java where a customer can select items he wants to order from a list with checkboxes and the quantity with spinners. I can generate the list of items through a for-loop (the items come from a Query to the database and return in an arrayList)

this is my for loop:

        ArrayList stringList = new ArrayList();
     stringList = cond.getOnderdelen(); // he gets the items from the database (method in other class)


    itemArea.add(new JLabel("Naam en prijs")); // itemArea is my JPanel

    for (int i = 0; i < stringList.size(); i++) {

            System.out.println(stringList.get(i));
            String item = (String) stringList.get(i);
            String checknummer = Integer.toString(i);
            check = new JCheckBox(checknummer);

            check.setText(item);
            JSpinner spin = new JSpinner();

            itemArea.setLayout(new BoxLayout(itemArea, BoxLayout.Y_AXIS));
            itemArea.add(check); // I add the components to the JPanel..
            itemArea.add(spin);

I get a nice boxlayout with 10+ items. But now the tricky part: how to know which checkbox is selected?? So I can make a button MAKE ORDER. It can only find the value of the last generated checkbutton ( so from the last item of the database)

if(e.getSource() == orderBtn) 
       {

           System.out.println("Button has been pressed");
           state = check.isSelected(); // state is a boolean variable.
           if(state == true)
           {

               System.out.println("True: checkbox is selected!");
           }

The problem would be solved if I can make more checkboxes with variabel names, like with the counter 'i' from the FOR loop. Then I can check whether checkbox1, checkbox2, checkbox3. .. is selected? But how?

Thanks in advance, Diederik Verstraete Student Business Engineer Ghent

1

1 Answers

0
votes

You can make multiple checkboxes and save them for later use in an array or collection. If you ActionListener is external to your class above, you will have to pass in the collection of checkboxes to the ActionListener somehow. If you use an anonymous one though, you can directly refer to your checkboxes.

 public class MyWindow extends JFrame()
 {
      private List<JCheckBox> checkboxes = new LinkedList<JCheckBox>();

      public MyWindow()
      {
         for (int i = 0; i < numOrders; ++i)
            checkboxes.add(new JCheckBox(String.valueOf(i));
      }

      // Not sure where you're action listener is, but here's the callback
      public void actionPerformed(ActionEvent event)
      {
          for (JCheckBox checkbox : checkboxes)
             System.out.println(checkbox.isSelected());
      }