0
...
float value = Float.parseFloat((String)model.getValueAt(e.getLastRow(), 1));             
DecimalFormat dec = new DecimalFormat("#.###");
model.setValueAt(dec.format(value), e.getLastRow(), 1);
...

at the third line i'm getting the stackOverflowError exception. What I'm intending to do is getting a JTable cell value from an Object, converting it to a float, limiting it to 3 decimal places, and finally convert to String and set the value with 3 decimal places at the cell.

I guess the problem is I'm changing the value, and entering the function again and again. So the StackOverflow is due to that. Question is, how can i fix this?

Complete function at: Java: Converting data types (Sorry for posting twice... It was a different question, and the solution drove me to a different problem)

Community
  • 1
  • 1
Roman Rdgz
  • 12,836
  • 41
  • 131
  • 207
  • 2
    Are you sure you are not calling yourself many times causing the error? What is the actual stack trace? – Peter Lawrey Jun 21 '11 at 10:57
  • I know the problem comes because the setValueAt triggers another tableChanged() event. But i don't know how to avoid it! – Roman Rdgz Jun 21 '11 at 10:59
  • Possible duplicate of [What is a StackOverflowError?](http://stackoverflow.com/questions/214741/what-is-a-stackoverflowerror) – Raedwald Jan 22 '16 at 13:21

4 Answers4

3

The problem is that setValueAt() will, as part of its implementation call tableChanged() on all registered listeners, including this one.

In order to avoid this, simply check whether the value in the cell is already in the desired format as the first thing in your method, and don't do anything if it is.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
1

Just don't call model.setValueAt() if value of the cell is not changed. It should stop the recursion.

SKi
  • 8,007
  • 2
  • 26
  • 57
1

I think this task is usually accomplished by setting a custom editor to the table. So that it formats all input data to a desired form. See this answer.

Community
  • 1
  • 1
Denis Tulskiy
  • 19,012
  • 6
  • 50
  • 68
0

Perhaps you need something like

String text = (String) model.getValueAt(e.getLastRow(), 1);
String text2 = new DecimalFormat("#.###").format(Float.parseFloat(text));
if (!text.equals(text2))
    model.setValueAt(dec.format(value), e.getLastRow(), 1);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130