简体   繁体   中英

StackOverflowError being caused by a TableModelListener

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.

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.

JTable.setValueAt causes a tablechanged event to fire, so you're calling the event handler repeatedly from within the event handler. Set the value in the model, not in the table.

You're updating a value in an event handler for updates. This will naturally trigger the event handler to be called again. Which will trigger the event handler to be called again, etc.

You'd need to perhaps remove the listener before making the update.

I was facing the same problem earlier when using jlist . My solution was to simply change the sequence of my lines of code.

  1. Get all the jpanel s which have images.
  2. Add a listener just before adding object[] to jlist

The issue I previously had (which was creating a stack-overflow error was adding the listener to jlist first, then getting all of the jpanel s with images.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM