日期:2014-05-20  浏览次数:20687 次

关于JComboBox的问题
界面有两个JComboBox,在combobox中选择一项后,在combobox_2中显示数据库中的相关信息,问题出在combobox_2中会重复显示数据,比如数据库中只有Mary一项,可在combobox_2中显示2个Mary,有谁帮我解决下问题啊,谢谢啦

comboBox = new JComboBox();
comboBox.addItemListener(new ItemListener(){  
public void itemStateChanged(ItemEvent ie) {  
try{
Class.forName("org.gjt.mm.mysql.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/rbac","root","1"); 
Statement cmd=con.createStatement();
if(comboBox.getSelectedIndex()==1){
ResultSet rs=cmd.executeQuery("select User_name from user "); 
while (rs.next()){  
comboBox_2.addItem(rs.getString("User_name"));  
}  
rs.close();  
con.close();  
cmd.close();
}
}catch(Exception ex){}
}  
});

comboBox.setBounds(240, 54, 123, 25);
getContentPane().add(comboBox);
comboBox.addItem("---请选择---");
comboBox.addItem("用户表");
comboBox.addItem("角色表");


------解决方案--------------------
增加清空

ResultSet rs=cmd.executeQuery("select User_name from user "); 
comboBox_2.removeAllItems()
while (rs.next()){
comboBox_2.addItem(rs.getString("User_name"));
}
rs.close();
con.close();
cmd.close(); 

}catch(Exception ex){} 
}
});
------解决方案--------------------
1楼说的是一个问题
另外请确定你用select User_name from user
到数据库中直接查询确实是一条