我正在制作一个GUI并且它包含一个JPanel,在JPanel内部有一个JTable,我想要做的是:当我点击一个按钮时,它们都会出现(因为我正在使用CardLayout)。代码:
private void teGjithaButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
parentPanel.setVisible(true);
parentPanel.removeAll();
parentPanel.add(tgjPanel);
parentPanel.repaint();
parentPanel.revalidate();
listAllCurtains();
} catch (SQLException ex) {
Logger.getLogger(MainBrillant.class.getName()).log(Level.SEVERE, null, ex);
}
}
listAllCurtains()的代码:
DefaultTableModel deftm = (DefaultTableModel) allTable.getModel();
if (deftm.getRowCount() != 0) {
deftm.setRowCount(0);
}
stm = (Statement) conn.createStatement();
ResultSet rs = stm.executeQuery("select * from customerregister.curtain inner join curtainrel on curtain.code = curtainrel.curtainCode;");
while (rs.next()) {
String shifra = rs.getString("code");
String ngjyra = rs.getString("color");
String emri = rs.getString("name");
double cmimi = rs.getDouble("price");
double sasia = rs.getDouble("amount");
allCurtains.add(new Curtain(shifra, ngjyra, emri, cmimi, sasia));
}
Object[] row = new Object[5];
for (int i = 0; i < allCurtains.size(); i++) {
row[0] = allCurtains.get(i).getShifra();
row[1] = allCurtains.get(i).getEmri();
row[2] = allCurtains.get(i).getNgjyra();
row[3] = allCurtains.get(i).getCmimi();
row[4] = allCurtains.get(i).getSasia();
deftm.addRow(row);
}
}
问题在于,当我重新点击按钮时,尽管有这部分代码可以确保数据不重复:
if (deftm.getRowCount() != 0) {
deftm.setRowCount(0);
}
每次单击按钮时,它仍然会继续将相同的数据插入表中。我无法弄清楚为什么会这样,我真的很感谢你的帮助。
答案 0 :(得分:1)
在您决定再次重新发布数据之前,可能应该清除其行的JTable模型。而不是你的:
if (deftm.getRowCount() != 0) {
deftm.setRowCount(0);
}
代码,也许使用简单的 clearTable()方法,如:
private void clearJTable(DefaultTableModel yourTableModel) {
while (yourTableModel.getRowCount() > 0) {
for (int i = 0; i < yourTableModel.getRowCount(); i++) {
yourTableModel.removeRow(i);
}
}
}
然后在你的代码中:
DefaultTableModel deftm = (DefaultTableModel) allTable.getModel();
clearJTable(deftm);
stm = (Statement) conn.createStatement();
ResultSet rs = stm.executeQuery("select * from customerregister.curtain inner join curtainrel on curtain.code = curtainrel.curtainCode;");
while (rs.next()) {
String shifra = rs.getString("code");
String ngjyra = rs.getString("color");
String emri = rs.getString("name");
double cmimi = rs.getDouble("price");
....................................
....................................
....................................