我有一个字段:
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
有什么不对吗?如何修改我的代码以消除此错误?
答案 0 :(得分:2)
我已经基于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/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://sourceforge.net/projects/softsmithy/files/softsmithy/
的Maven:
<dependency>
<groupid>org.softsmithy.lib</groupid>
<artifactid>lib-core</artifactid>
<version>0.1</version>
</dependency>
-Puce
答案 1 :(得分:2)
你可以试试这个:
JFormattedTextField ftf = new JFormattedTextField();
ftf.setFormatterFactory(new DefaultFormatterFactory(
new NumberFormatter(new DecimalFormat("#,##0.00"))));
// Input = 1245678.57
// After the format it will be:
// 1,245,678.57
// So, we need to get rid of the comma's:
String number = ftf.getText().replace(",","");
BigDecimal bd = new BigDecimal(number);