2016-01-07 53 views
0

我有JTable,我可以更新和删除行。我的问题是,当我想打印出记录表刷新,但是当我删除/更新它不。为什么刷新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

1)为了更好地提供帮助,请发布[MCVE]或[简短,独立,正确的示例](http://www.sscce.org/)。 2)为什么实现'AbstractTableModel'而不是扩展'DefaultTableModel'?这个问题可能在表模型中。 –

+0

该行如何从“TableModel”中实际删除? – MadProgrammer

回答

4

您PrisonerTableModel不必从TableModel的删除数据行的方法。如果你想从表中删除数据,那么你需要从TableModel中删除数据。 TableModel将调用fireTableRowsDeleted(...)方法。您的应用程序代码不应该调用TableModel的fireXXX(...)方法。

去除数据行会是这样的基本逻辑:

public void removePrisoner(int row) 
{ 
    db.remove(row); 
    fireTableRowsDeleted(row, row); 
} 

退房Row Table Model对于如何更好地实现你的TableModel逻辑更完整的示例。

相关问题