Search code examples
javaswingjcombobox

ArrayList of JComboBoxes


I created an ArrayList of JComboBox

private static ArrayList<JComboBox> comboList = new ArrayList<>();

and then added each instance of JComboBox to the ArrayList

private void courseUnit() {
        String[] units = {"6", "5", "4", "3", "2", "1"};
        int x = 520, y = 30;
        for (int i = 0; i < 10; i++) {
            comboUnits = new JComboBox<>(units);
            comboUnits.setBounds(x, y, 100, 25);
            y += 30;
            comboUnits.setToolTipText("Select course unit");
            comboUnits.setVisible(true);
            comboUnits.addActionListener(new PaneAction());
            add(comboUnits);
            comboList.add(comboUnits); //comboUnits added to ArrayList
        }
    }

My question is, how do i get the selectedItem from each comboBox in the ArrayList because i tried this

//this is supposed to get the selected item of the first ComboBox and assign to courseGrade[0]
    public void actionPerformed(ActionEvent evt) {
            String[] courseGrade = new String[10];
            courseGrade[0] = (String)comboList.get(0).getSelectedItem();

and the program didn't compile.


Solution

  • You can should attach ActionListner while you are adding the JComboBox to the ArrayList

        private void courseUnit() {
                String[] units = {"6", "5", "4", "3", "2", "1"};
                int x = 520, y = 30;
                for (int i = 0; i < 10; i++) {
                    comboUnits = new JComboBox<>(units);
                    comboUnits.setBounds(x, y, 100, 25);
                    y += 30;
                    comboUnits.setToolTipText("Select course unit");
                    comboUnits.setVisible(true);
                    //comboUnits.addActionListener(new PaneAction());
                    add(comboUnits);
    
    //////////////// Here are the changes
    
                    comboUnits.addActionListener (new ActionListener () {
                       public void actionPerformed(ActionEvent e) {
                          String selectedItem = (String)e.getSelectedItem();
                       }
                    });
                    comboList.add(comboUnits); //comboUnits added to ArrayList
                }
            }