2014-02-15 69 views
0

刪除JTable的自動刷新不工作的項目...刷新JTable中後刪除一個項目從數據庫

這裏是代碼

@Override 
    public void actionPerformed(ActionEvent e) { 
     if (e.getSource() == btnEdit) { 


     } else if (e.getSource() == btnDelete) { 

      String str = JOptionPane.showInputDialog(null, 
        "Enter The Reason : ", "", 1); 


      if (str != null) { 
       Book updatebook = new Book(); 
       updatebook.setName(book.getName());       
       updatebook.setAuthor(book.getAuthor()); 
       updatebook.setPublisher(book.getPublisher()); 
       updatebook.setDelete(true); 
       ServiceFactory.getBookServiceImpl().updateBook(updatebook); 

       JOptionPane.showMessageDialog(null, "You entered the Reason : "+ str, "", 1); 

     **Refresh code** 

       listPanel.removeAll(); 
       listPanel.repaint(); 
       listPanel.revalidate(); 
       getBooks(); 
       getListBookPanel(); 
       booktable.repaint(); 
       booktable.revalidate(); 


      } else 
       JOptionPane.showMessageDialog(null, 
         "You pressed cancel button.", "", 1); 

     } 
    } 

getBooks()函數

public JTable getBooks() { 
    booktable = new JTable(); 

    String[] colName = { "Name", "Author ", 
      "Publisher" }; 
    List<Book> books = ServiceFactory.getBookServiceImpl().findAllBook(); 
    data = new Object[books.size()][100000]; 

    for (Book book : books) { 

     data[i][0] = book.getName(); 
     data[i][1] = book.getAuthor(); 
     data[i][2] = book.getPublisher(); 
     i++; 
    } 
DefaultTableModel dtm = new DefaultTableModel(data, colName); 
    booktable = new JTable(); 
    booktable.setModel(dtm); 

    dtm.fireTableDataChanged(); 
    booktable.setCellSelectionEnabled(true); 
    booktable.addMouseListener(new MouseAdapter() { 
     public void mouseClicked(MouseEvent e) { 

      int row = booktable.getSelectedRow(); 
      CallNo = (booktable.getValueAt(row, 0).toString()); 

     } 
    }); 

    return booktable; 

} 

錯誤

「AWT-EventQueue的 - 0」 java.lang.ArrayIndexOutOfBoundsException:2

我不知道爲什麼,如果u知道這件事,請在這裏分享這個錯誤發生..

+0

您是否嘗試刪除整個表格並創建另一個表格然後將其添加回來? –

+0

你究竟想要移除什麼?只是一個單元格,還是一排? –

+0

@peeskillet我試圖從表格中刪除一個項目,表格刪除刪除項目... –

回答

2

你嘗試的方式刪除數據似乎變化不大效率,只是不正確。它看起來像你想要做的與你的代碼是創建一個完整的其他表並將其替換爲一個新的。不要這樣做。只需更新TableModel。您可以使用其方法

只要使用這種方法,就會自動從表格中刪除一行。所以,你可以做這樣的事情,在某個地方的監聽

DefaultTableModel model = (DefaultTableModel)bookTable.getModel(); 
int row = ... 
model.removeRow(row); 

所有你的代碼,你必須**Refresh code**看起來完全沒有必要。

查看DefualtTableModel瞭解更多方法,例如添加行等。

+1

thanqs alot ..它真的工作... –

相關問題