user3600952
user3600952

Reputation:

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!)

Upvotes: 0

Views: 219

Answers (1)

Braj
Braj

Reputation: 46841

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.

Upvotes: 1

Related Questions