Java StackOverflowError

2019-06-11 10:41发布

...
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)

4条回答
\"骚年 ilove
2楼-- · 2019-06-11 11:21

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.

查看更多
相关推荐>>
3楼-- · 2019-06-11 11:25

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.

查看更多
何必那么认真
4楼-- · 2019-06-11 11:25

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

查看更多
手持菜刀,她持情操
5楼-- · 2019-06-11 11:36

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);
查看更多
登录 后发表回答