2013-05-12 132 views
2

好吧,我已經閱讀了這個,但我仍然很困惑。我有一個帶有定製表模型的JTable,它將數據存儲在ArrayList中。它顯示得很好。但是,當我想添加一行時,我向ArrayList添加一個對象,然後調用fireTableRowsInserted(...)。但是,表不刷新。當模型更新時JTable不更新

public Main() { 
     initComponents(); 
     current_map = new Map(); 
     current_map.authors.add(new Author("New Author")); 
     author_model = new AuthorModel(current_map.authors); 
     jTable1.setModel(new AuthorModel(current_map.authors)); <---This is the mistake 
    } 
...  



    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {           
     author_model.authors.add(new Author("New Author")); 
     author_model.fireTableRowsInserted(author_model.authors.size(), author_model.authors.size()); 
    } 

上面的代碼是從我的主要JFrame。不知道該從哪裏出發。

我迷路了。

jTable1.setModel(new AuthorModel(current_map.authors)); 

但單擊該按鈕時,您修改變量author_model:

+0

不要直接調用TableModel的fireXXX方法。這些方法只能由TableModel類本身調用。 – camickr 2013-05-13 05:41:17

+0

啊,所以更新會自動發生呢?我會試試看。 – 2013-05-13 17:22:29

回答

4

表與初始化

author_model.authors.add(new Author("New Author")); 

表的初始化應該是

jTable1.setModel(author_model); 

您還應該尊重Java命名約定,併爲變量選擇更好的名稱。

+0

哦,呃,我怎麼錯過那個。我知道名字不好,他們是暫時的。 – 2013-05-12 21:56:05

+3

author_model應該是authorModel。與current_map相同。變量在Java中是camelCased的。 – 2013-05-12 21:56:44

+0

重要答案。謝謝 – 2013-05-12 22:00:49