有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

有什么问题吗?如何修改代码以消除此错误


共 (2) 个答案

  1. # 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/

    马文:

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

    -普塞

  2. # 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);