我有一个用来自mysqlcombobox
的数据填充它,我目前遇到的问题是它重复了这些值,例如,如果我添加 5 个项目,它将显示第 5 个和另外 5 个是第一个项目的副本,我留下代码和示例照片:combobox
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++;
}
}
我希望你能帮帮我
应@gbianchi 的要求,问题似乎是由itemStateChanged本身引起的,因为该事件被正常调用两次。
第一次选中项变为未选中(即其状态变为unselected),第二次选中新项时(从unselected变为 selected)。
正如我在评论中提到的:
所以,最好使用JComboBox的ActionListener的ActionPerformed。
如果强制您必须使用ItemStateChanged然后,请检查项目的状态是否为“已选择”,这样您就获得了该项目并且它不会发生两次,您将获得该项目的状态
e.getStateChanged();
我是这样做的,首先我在数据访问层创建了一个结果集类型的方法。
我执行句子的地方
sql
然后在视图窗体中,我创建了一个加载数据的方法,并在类的构造函数方法中启动它。