Java StackOverflowError
...
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 St开发者_StackOverflow中文版ring 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)
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.
Just don't call model.setValueAt() if value of the cell is not changed. It should stop the recursion.
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.
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);
精彩评论