简体   繁体   中英

Selected combobox value added twice to an arraylist

I've populated the elements of a combo box using a SQL query and am writing the selected value to an arraylist. When I print out the elements of the arraylist, the value has been added twice. Does anybody know why this is, and how do I stop this from happening?

Extracts from the code:

resultSet = statement.executeQuery("SELECT name FROM menu WHERE category = 'beverage'");
while (resultSet.next())
{
    beverageJComboBox.addItem(resultSet.getString(1));
    System.out.printf("%s", resultSet.getString(1));
}

And for the adding ite to the ArrayList:

beverageJComboBox.addItemListener(
     new ItemListener()
     {
          public void itemStateChanged( ItemEvent event )
          {
              billItems.add((String)beverageJComboBox.getSelectedItem());
              System.out.printf("%s", billItems); 
          }
     }// end anonymous inner class
); 

(Very new to Java!)

Use ActionListener instead of ItemListener

    beverageJComboBox.addActionListener (new ActionListener () {
        public void actionPerformed(ActionEvent e) {
            ...
        }
    });

Note: use distinct keyword in query itself to show the unique record in JComboBox .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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