user2146545
user2146545

Reputation:

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? 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():

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

}

Upvotes: 0

Views: 1569

Answers (1)

jzd
jzd

Reputation: 23639

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

Upvotes: 3

Related Questions