2012-10-28 108 views
2

我期待在jtable中更改單元格的數據。我怎樣才能做到這一點?當我執行下面的代碼時,我得到錯誤。Java JTable,如何更改單元格數據(寫入文本)?

JFrame f= new JFrame(); 
final JTable table= new JTable(10,5); 

TableModelListener tl= new TableModelListener(){ 
    public void tableChanged(TableModelEvent e){ 

    table.setValueAt("hello world",2,2); 
    } 
}; 

table.getModel().addTableModelListener(tl); 
f.add(table); 
f.pack(); 
f.setVisible(true); 

我也在下面嘗試過,但它仍然不起作用。是什麼賦予了?

table.getModel().setValueAt("hello world",2,2); 
+0

你的意思是_doesn't work_? – kleopatra

+0

它不編譯。我的問題很簡單:當一個jtable單元格值發生變化時,我想編輯一個特定的單元格 – thecodefather

+0

然後先修復編譯錯誤。 – kleopatra

回答

3

調用TableModelListenertable.setValueAt()使tableChanged()方法 被稱爲接着setValueAt()方法被再次和所謂的上循環往復,導致StackOverflowError

一種解決方案是使用CellEditorListener代替。請參閱example

+0

這並不能真正解決我的問題。當jtable出現問題時,我將如何寫入單元格? – thecodefather

+1

我想你正在尋找'CellEditorListener'。請參閱上面示例的鏈接。 – Reimeus

+1

'tableChanged'告訴你已經發生了一些事情 – MadProgrammer

0

你可以使用Rob Camick的例子,幫助我很多,另外你也可以通過使用這個類獲得新舊價值。 Example

另請參見博客的結尾以查看我的帖子,以將添加代碼添加到表單加載事件以處理髮生在表格上的最後更改。

MouseEvent me = new MouseEvent(tblDetailInfo, 0, 0, 0, 100, 100, 1, false); 
for(MouseListener ml: tblDetailInfo.getMouseListeners()){ 
ml.mouseClicked(me); } 
+0

對不起,但這不是我要找的無論是。我的問題很簡單:當一個jtable單元格值被改變時,我想編輯一個特定的單元格。 – thecodefather