【问题标题】:How to use BigDecimal with JFormattedTextField如何将 BigDecimal 与 JFormattedTextField 一起使用
【发布时间】:2011-05-22 17:18:04
【问题描述】:

我有一个字段:

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

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

【问题讨论】:

  • 要在JTable 上下文中使用,请参阅DecEditor,它允许BigDecimalDefaultCellEditor 中使用。

标签: java swing netbeans bigdecimal jformattedtextfield


【解决方案1】:

你可以试试这个:

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);
【解决方案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>  

-普斯

【讨论】:

    猜你喜欢
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 2023-03-13
    • 2014-09-25
    • 2016-01-30
    • 2015-12-13
    相关资源
    最近更新 更多