I have one combobox
that fills it with data from mysql , the problem I currently have is that combobox
it duplicates the values, for example, if I add 5 items, it will show me the 5 and another 5 that are copies of the first ones, I leave you the code and an example photo:
public void docenteAlumno(String seccion,JComboBox cb,JComboBox cb2,DocenteMenu estado){
ArrayList <String> usuarios= new ArrayList();
Connection con= new AbrirBasedeDatos().conectar();
int yy=cb.getItemCount();
String xx=String.valueOf(yy);
if(xx!=null && !xx.isEmpty()){
cb.removeAll();
}
usuarios.clear();
cb.addItem("Seleccione Alumno");
try {
if(con!=null){
Statement st = con.createStatement();
String query ="select * from inasistencia where seccion = '"+seccion+"'and leida=false and justificado='si'";
ResultSet rs = st.executeQuery(query);
while(rs.next()){
usuarios.add(rs.getString("user"));
}
removeDuplicates(usuarios);
for(int i=0;i<usuarios.size();i++){
String query2="select * from usuario where user='"+usuarios.get(i)+"'";
ResultSet rss=st.executeQuery(query2);
while(rss.next()){
cb.addItem(rss.getString("nombre"));
}
}
cb2.setEnabled(true);
}else{
JOptionPane.showMessageDialog(estado,"Asegurate de estar conectado a internet");
}
}catch (SQLException sqle){
System.out.println("el error fue: "+sqle.getMessage());
JOptionPane.showMessageDialog(estado,"Ocurrio un error, vuelve a intentarlo más tarde");
}
new AbrirBasedeDatos().cerrarConexion();
}
private void removeDuplicates(ArrayList<String> list){
int index = 0;
int count = 0;
while (index < list.size() - 1) {
String item = list.get(index);
List<String> tail = list.subList(index + 1, list.size());
while (tail.equals(item)) {
tail.remove(item);
count++;
}
index++;
}
}
This is how it currently looks:
I hope you can help me
At the request of @gbianchi, it seems that the problem is caused by the itemStateChanged itself , since this event is called twice as normal.
The first time when the selected item becomes unselected (that is, its state changes to unselected ) and the second time when the new item is selected (changes from unselected to selected ).
As I mentioned in the comment:
So, it is better to use the ActionPerformed of the ActionListener of the JComboBox .
If by force you must use the ItemStateChanged then, check with an if if the state of the item is "selected", so you get the item and it won't happen twice, you get the state of the item with
e.getStateChanged();
I do it this way, first I create a method of type resultset in the data access layer.
It is there where I execute the sentence
sql
And then in the view form I create a method to load the data and start it in the constructor method of the class.