1

我有一个字段:

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

有什么不对的吗?如何修改我的代码以消除此错误?

4

2 回答 2

3

你可以试试这个:

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);
于 2011-05-22T17:32:30.880 回答
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/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/

马文:

<dependency>  
    <groupid>org.softsmithy.lib</groupid>  
    <artifactid>lib-core</artifactid>  
    <version>0.1</version>  
</dependency>  

-普斯

于 2011-05-22T17:28:14.713 回答