我正在尝试为桌面编写Java n层应用程序,我需要填充JComboBox。 DAO中的ResultSet读取15行,但是当我将ArrayList发送到JComboBox时,它仅显示最后一项。怎么了?
在这里DAO:
public static ArrayList<AbastosOpLog> LisAbasDisp(){
ArrayList <AbastosOpLog> abastosop = new ArrayList<>();
Conexion conex = new Conexion();
AbastosOpLog abasop = new AbastosOpLog();
String consulta = "select abop001.abascod, abop001.abasdesc from abop001";
try{
Statement st = null;
ResultSet rs = null;
st = conex.getConnection().createStatement();
rs = st.executeQuery(consulta);
if(conex != null){
while (rs.next())
{
abasop.setAbas_cod(rs.getString("abascod"));
abasop.setAbas_desc(rs.getString("abasdesc"));
abastosop.add(abasop);
}
}
rs.close();
st.close();
conex.desconectar();
}catch (SQLException e) {
System.out.println("Error."+e.getMessage());
}
逻辑类:
public class AbastosOpLog {
private String abas_cod;
private String abas_desc;
//
public String getAbas_cod() {
return abas_cod;
}
public void setAbas_cod(String abas_cod) {
this.abas_cod = abas_cod;
}
public String getAbas_desc() {
return abas_desc;
}
public void setAbas_desc(String abas_desc) {
this.abas_desc = abas_desc;
}
}
视图:
private void LlenarOpAbastos() {
cblisopt.removeAllItems();
ArrayList <AbastosOpLog> abastoop = AbastosOpDao.LisAbasDisp();
for (int i = 0; i < abastoop.size(); i++) {
cblisopt.addItem(abastoop.get(i).getAbas_cod()); // + " - " + abastoop.get(i).getAbas_desc());
}
}
结果如下:
谢谢
答案 0 :(得分:4)
while (rs.next())
{
abasop.setAbas_cod(rs.getString("abascod"));
abasop.setAbas_desc(rs.getString("abasdesc"));
abastosop.add(abasop);
}
您要一遍又一遍地添加相同的实例。在每次迭代中创建一个新实例(也删除先前的声明):
while (rs.next())
{
AbastosOpLog abasop = new AbastosOpLog();
abasop.setAbas_cod(rs.getString("abascod"));
abasop.setAbas_desc(rs.getString("abasdesc"));
abastosop.add(abasop);
}