3

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);
mKorbel
  • 109,525
  • 20
  • 134
  • 319

2 Answers2

3

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.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

You can use Rob Camick's example that help me alot, in addition you can get old and new value also by using this class. Example!

Also look at the end of Blog to see my post to Add Addiional Code to the Form Load Event To Handle Last Change Occur To Your Table.

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