Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StackOverflowError being caused by a TableModelListener

Tags:

java

swing

jtable

I'm not sure why this is recursing.

jTable1.getModel().addTableModelListener(new TableModelListener() {

 public void tableChanged(TableModelEvent evt) {
  int sum = 0;
  int i=0;
  for (i =0 ; i<2; i++){
   sum = sum + Integer.parseInt(jTable1.getValueAt(0, i).toString());
  }
  jTable1.setValueAt(sum, 0, 2);
 }

}); 

The exception is: (it keeps repeating)

Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
        at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
        at javax.swing.JTable.convertColumnIndexToModel(JTable.java:2553)
        at javax.swing.JTable.getValueAt(JTable.java:2695)
        at testprogram.guitest.TestTableModel$1.tableChanged(TestTableModel.java:63)
        at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:280)
        at javax.swing.table.AbstractTableModel.fireTableCellUpdated(AbstractTableModel.java:259)
        at javax.swing.table.DefaultTableModel.setValueAt(DefaultTableModel.java:650)
        at javax.swing.JTable.setValueAt(JTable.java:2719)

Any help appreciated.

like image 877
me_here Avatar asked Apr 19 '10 15:04

me_here


1 Answers

From the event handler (tableChanged method) wrap your code that makes use of setValue method with code to remove and add the listener, like this

public void tableChanged(TableModelEvent e) {
model.removeTableModelListener(this);
// YOUR CODE WITH setValueAt calls begins here
if (ppt == null || cantidad > ppt.getStock()) {

model.setValueAt(ppt != null ? ppt.getStock() : 0, e.getFirstRow(), 3);
}

model.setValueAt(precioUnitario * cantidad, e.getFirstRow(), 4);

// YOUR CODE with setValueAt calls ends here
model.addTableModelListener(this);
}

This will disable temporarily the listener while you work on validations.

like image 88
Jaime Hablutzel Avatar answered Nov 09 '22 10:11

Jaime Hablutzel