简体   繁体   English

在JCOMBOBOX中重复值

[英]Repeating Values inside JCOMBOBOX

I'm trying to update the Value inside a JComboBox but the problem is when I add or delete a value all of the names inside the JComboBox is repeated how can I fix this? 我正在尝试更新JComboBox内的值,但是问题是当我添加或删除值时, JComboBox内的所有名称都重复了,我该如何解决呢? I tried to put it after connection close but it didn't work 连接关闭后我尝试将其放上,但没有用

Here is my Code: 这是我的代码:

  private void cmbNamesPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {                                                      

  try{

     String tmp=(String)cmbNames.getSelectedItem();    
     String sql="SELECT * FROM Account WHERE Fname=?";
     pst=conn.prepareStatement(sql);
     pst.setString(1,tmp);
     rs=pst.executeQuery();

     if(rs.next()){              
          String add1=rs.getString("ID");
          txtID.setText(add1);              
          String add2=rs.getString("Fname");
          txtFirst.setText(add2);              
          String add3=rs.getString("Lname");
          txtLast.setText(add3);              
          String add4=rs.getString("Username");
          txtUser.setText(add4);            
          String add5=rs.getString("Password");
          txtPass.setText(add5);            
          cmdUpdate.setEnabled(true);
          cmdDelete.setEnabled(true);
          cmdAdd.setEnabled(false);              
      }            
    }        
    catch(SQLException e){
    JOptionPane.showMessageDialog(null,e);     
    }
}

and here is the code I used in Names(): 这是我在Names()中使用的代码:

     private void Names(){

      try{
        String sql="Select fname from account";
        pst=conn.prepareStatement(sql);
        rs=pst.executeQuery();

        while(rs.next()){
            String name=rs.getString("fname");
            cmbNames.addItem(name);

        }
        rs.close();
         pst.close(); 
    }

    catch(SQLException e){
         JOptionPane.showMessageDialog(null,e); 
    }
    finally{
     try{
         rs.close();
         pst.close();

     }
     catch(SQLException e){
           JOptionPane.showMessageDialog(null,e); 
     }
 }

}

Your update from the database add items from a query. 您从数据库进行的更新会添加查询中的项目。 Each time you run this it is only going to keep adding items. 每次运行此命令只会继续添加项目。 Clear the combo box before you run the update. 在运行更新之前,请清除组合框。

For example, add this line before you loop through your result set. 例如,在遍历结果集之前添加此行。

cmbNames.removeAllItems();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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