【问题标题】:Selected combobox value added twice to an arraylist选定的组合框值两次添加到数组列表
【发布时间】:2014-06-20 16:44:49
【问题描述】:

我已经使用 SQL 查询填充了组合框的元素,并将所选值写入数组列表。当我打印出 arraylist 的元素时,该值已添加两次。有谁知道这是为什么,我该如何阻止这种情况发生?

代码摘录:

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));
}

对于向 ArrayList 添加 ite:

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

(Java 新手!)

【问题讨论】:

    标签: java swing arraylist jcombobox itemlistener


    【解决方案1】:

    使用ActionListener 代替ItemListener

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

    注意:在查询本身中使用distinct关键字来显示JComboBox中的唯一记录。

    【讨论】:

      猜你喜欢
      • 2015-03-21
      • 1970-01-01
      • 2014-08-27
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      相关资源
      最近更新 更多