我有JTable,我可以更新和删除行。我的问题是,当我想打印出记录表刷新时,但当我删除/更新时却没有。
PrisonerEvent包含要在数据库中删除的数据。这没有问题。这是我的倾听者:
class DeletePrisonerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
int row = getSelectedRow();
PrisonerEvent evt = getPrisonerEvent();
String message = "Are you sure you want to delete this prisoner?";
int option = JOptionPane.showOptionDialog(null, message, "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
if(option == JOptionPane.OK_OPTION) {
prisonerController.removePrisoner(evt.getId());
}
tablePanel.getTableModel().fireTableDataChanged();
}
}
这是我的TableModel
public class PrisonerTableModel extends AbstractTableModel {
private List<Prisoner> db;
private String[] colNames = { "Name", "Surname", "Date of birth", "Height", "Eye color", "Hair color",
"Country of origin", "Gender"};
public PrisonerTableModel(){
}
public String getColumnName(int column) {
return colNames[column];
}
public void setData(List<Prisoner> db) {
this.db = db;
}
public int getColumnCount() {
return 8;
}
public int getRowCount() {
return db.size();
}
public Object getValueAt(int row, int col) {
Prisoner prisoner = db.get(row);
switch(col) {
case 0:
return prisoner.getName();
case 1:
return prisoner.getSurname();
case 2:
return prisoner.getBirth();
case 3:
return prisoner.getHeight();
case 4:
return prisoner.getEyeColor();
case 5:
return prisoner.getHairColor();
case 6:
return prisoner.getCountry();
case 7:
return prisoner.getGender();
}
return null;
}
}
答案 0 :(得分:4)
您的PrisonerTableModel没有从TableModel中删除一行数据的方法。如果要从表中删除数据,则需要从TableModel中删除数据。然后TableModel将调用fireTableRowsDeleted(...)
方法。您的应用程序代码永远不应该调用TableModel的fireXXX(...)方法。
删除一行数据的基本逻辑如下:
public void removePrisoner(int row)
{
db.remove(row);
fireTableRowsDeleted(row, row);
}
查看Row Table Model以获取更完整的示例,了解如何更好地在TableModel中实现逻辑。