2016-01-07 54 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邏輯更完整的示例。

相關問題