Search code examples
javadropdownchoice

Adding options to multiple 'choice' objects in java


The for loop isn't working. I get "Choice cannot be resolved to a variable". I would like to add a group of options to multiple Choice objects added to the generics list. In this example you can see one of these objects (DidWell1) .

import java.awt.Choice;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;


public class testing {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    testing window = new testing();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public testing() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final Choice DidWell1 = new Choice();
        DidWell1.setBounds(119, 36, 135, 20);
        frame.getContentPane().add(DidWell1);

        List<Choice> list = new ArrayList<Choice>();

        list.add(DidWell1);

        String option = "Friday";

        For(Choice choice: list){
            choice.add( option );
        }
    }

}

Solution

  • Create a list of Choice objects

    List<Choice> list = new ArrayList<Choice>();
    

    Next add all Didwells to this list.

    list.add( didwell1 ); etc
    

    With this setup adding new options can be done using a For loop:

    String option = "Friday";
    
    for( Choice choice: list ){
        choice.add( option );
    }
    

    Or with a While loop:

    Iterator<Choice> iter = new list.iterator();
    while iterator.hasNext(){
        iter.next().add( option );
    }