java如何将BigDecimal与JFormattedTextField一起使用
我有一个字段:
jFormattedTextFieldGrossWeight = new javax.swing.JFormattedTextField();
jFormattedTextFieldGrossWeight.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00"))));
我使用其setValue()方法为其分配一个BigDecimal值,并允许用户使用此文本字段修改该值
然后在lostFocus方法中,在线:
jFormattedTextField.commitEdit();
BigDecimal gross = (BigDecimal)this.jFormattedTextFieldGrossWeight.getValue();
我得到以下例外情况:
java.lang.ClassCastException: java.lang.Long cannot be cast to java.math.BigDecimal
有什么问题吗?如何修改代码以消除此错误
# 1 楼答案
我已经基于JFormattedTextField实现了数字字段
JRealNumberField和JLocalizedRealNumberField是BigDecimal的文本字段
它们还支持最小值和最大值
也许您会发现它们很有用(该库是开源的):
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JRealNumberField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JDoubleField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JFloatField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JLocalizedRealNumberField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JLocalizedDoubleField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JLocalizedFloatField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JWholeNumberField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JByteField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JIntegerField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JLongField.html
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/swing/JShortField.html
教程:
http://softsmithy.sourceforge.net/lib/docs/tutorial/swing/number/index.html
主页:
http://www.softsmithy.org
下载:
http://sourceforge.net/projects/softsmithy/files/softsmithy/
马文:
-普塞
# 2 楼答案
您可以尝试以下方法: