我有一个使用ArrayList从数据库加载数据的JTable,但我有一个问题,即相同的数据不断重复。 我在这里失踪了什么?提前谢谢,
private void AllTicketRecords() {
try {
TicketRecordDao ticketrecdao = new TicketRecordDao();
ArrayList<TicketRecord> records = ticketrecdao.getAllTicketsRecords();
Object[] tableColumnName = new Object[7];
tableColumnName[0] = "Date";
tableColumnName[1] = "H.License";
tableColumnName[2] = "First Name";
tableColumnName[3] = "Last Name";
tableColumnName[4] = "Ticket ID";
tableColumnName[5] = "Violation";
tableColumnName[6] = "Cost";
DefaultTableModel tbd = new DefaultTableModel();
tbd.setColumnIdentifiers(tableColumnName);
this.TicketsSummaryTable.setModel(tbd);
Object[] RowRec = new Object[7];
for (int i = 0; i < records.size(); i++) {
RowRec[0] = records.get(i).getDATE();
RowRec[1] = records.get(i).getEMP_ID();
RowRec[2] = records.get(i).getFNAME().toUpperCase();
RowRec[3] = records.get(i).getLNAME().toUpperCase();
RowRec[4] = records.get(i).getTICKET_ID();
RowRec[5] = records.get(i).getVIOLATION();
RowRec[6] = nf.format(records.get(i).getCOST());
tbd.addRow(RowRec);
}
} catch (SQLException e) {
System.out.println(e.toString());
}
}
public ArrayList<TicketRecord> getAllTicketsRecords() throws SQLException {
String sql = "SELECT DATE, T.EMP_ID ,E.FNAME, E.LNAME ,TICKET_ID, VIOLATION, COST"
+ " FROM EMPLOYEE E INNER JOIN TICKET T ON E.EMP_ID = E.EMP_ID"
+ " ORDER BY DATE";
DBConnection con = new DBConnection();
Connection connect = con.getConnection();
Statement stm = null;
ArrayList<TicketRecord> records = new ArrayList<>();
try {
stm = connect.createStatement();
ResultSet rs = stm.executeQuery(sql);
while (rs.next()) {
TicketRecord tickterec = new TicketRecord();
tickterec.setDATE(rs.getString("DATE"));
tickterec.setEMP_ID(rs.getInt("EMP_ID"));
tickterec.setFNAME(rs.getString("FNAME"));
tickterec.setLNAME(rs.getString("LNAME"));
tickterec.setTICKET_ID(rs.getString("TICKET_ID"));
tickterec.setVIOLATION(rs.getString("VIOLATION"));
tickterec.setCOST(rs.getDouble("COST"));
records.add(tickterec);
}
} catch (SQLException e) {
System.out.println("" + e.toString());
} finally {
if (connect != null) {
connect.close();
}
if (stm != null) {
stm.close();
}
}
return records;
}
答案 0 :(得分:2)
问题的主要原因似乎与......相关。
Object[] RowRec = new Object[7];
for (int i = 0; i < records.size(); i++) {
RowRec[0] = records.get(i).getDATE();
基本上,您使用RowRec
的相同实例,但只是更改数组的元素,这将影响以前添加的所有其他行。
相反,为每一行创建RowRec
的新实例......
for (int i = 0; i < records.size(); i++) {
Object[] RowRec = new Object[7];
RowRec[0] = records.get(i).getDATE();
我还要验证您的数据库结果,以确保没有任何重复项,以确保;)
在侧节点上,我只是创建一个自定义TableModel
,从AbstractTableModel
扩展,可以直接使用TicketRecord
,而不是分解现有的记录值DefaultTableModel
,但那是我