Java JTable, how to change cell data (write text in)?

thecodefather picture thecodefather · Oct 29, 2012 · Viewed 16.3k times · Source

Am looking to change a cell's data in a jtable. How can I do this? When I execute the following code I get errors.

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);

I have also tried this below but it still doesn't work. What gives?

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

Answer

Reimeus picture Reimeus · Oct 29, 2012

Calling table.setValueAt() within a TableModelListener causes the tableChanged() method to be called followed by the setValueAt() method being called again and so on ad infinitum, resulting in a StackOverflowError.

One solution is to use a CellEditorListener instead. See this example.