学年模式
public class SchoolYear {
int id;
int start;
int end;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
}
SchoolYearDaoImpl类方法
public List<SchoolYear> getAllSchoolYearStart() {
String SQL = "{CALL getAllSchoolYearInfo()}";
SchoolYear schoolyear = new SchoolYear();
List<SchoolYear> list = new ArrayList<>();
try(Connection con = DBUtil.getConnection(DBType.MYSQL);
CallableStatement cs = con.prepareCall(SQL);){
try(ResultSet rs = cs.executeQuery();){
while(rs.next()){
schoolyear.setStart(rs.getInt("yearFrom"));
list.add(schoolyear);
}
JOptionPane.showMessageDialog(null,list.size());
for(int x=0; x<list.size(); x++){
JOptionPane.showMessageDialog(null,((SchoolYear)list.get(x)).getStart());
}
}
}catch(SQLException e){
JOptionPane.showMessageDialog(null,e.getMessage());
}
return list;
}
通过调用存储过程
getAllSchoolYearInfo()
获得的结果集显示yearFrom列有2行。但是,当我运行程序以查看GUI上的内容时,我在
JComboBox
中得到2个值,这似乎是第2行的值2015如您所见,我试图获取列表的大小,以查看存储了多少个对象。因此,我猜测在此代码块中如何将对象存储和累积到
List<SchoolYear>
可能是一个问题。try(ResultSet rs = cs.executeQuery();){
while(rs.next()){
schoolyear.setStart(rs.getInt("yearFrom"));
list.add(schoolyear);
}
JOptionPane.showMessageDialog(null,list.size());
for(int x=0; x<list.size(); x++){
JOptionPane.showMessageDialog(null,((SchoolYear)list.get(x)).getStart());
}
}
还是问题出在我的
ListCellRenderer
上?我认为不是。jcmbSchoolYearStart.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(value instanceof SchoolYear){
SchoolYear schoolyear = (SchoolYear) value;
setText(""+schoolyear.getStart());
}
return this;
}
} );
有什么想法吗?
谢谢。
最佳答案
您仅创建一个SchoolYear
实例。因为这样做,所以list
中只有一个引用。您可以注释掉当前的SchoolYear schoolyear
并将其移入循环(并修复所使用的其他位置),也可以像在循环中声明一个新的局部变量。
while(rs.next()){
SchoolYear sy = new SchoolYear();
sy.setStart(rs.getInt("yearFrom"));
list.add(sy);
}