I have a field as:
jFormattedTextFieldGrossWeight = new javax.swing.JFormattedTextField();
jFormattedTextFieldGrossWeight.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00"))));
I assign it a BigDecimal value using its setValue() method, and allow the user to modify that value using this textfield.
Then in the lostFocus method, on the line:
jFormattedTextField.commitEdit();
BigDecimal gross = (BigDecimal)this.jFormattedTextFieldGrossWeight.getValue();
I get the following exception:
java.lang.ClassCastException: java.lang.Long cannot开发者_Python百科 be cast to java.math.BigDecimal
Is there anything wrong? How can I modify my code to get rid of this error?
You can try this:
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);
I've implemented number fields based on JFormattedTextField.
JRealNumberField and JLocalizedRealNumberField are text fields for BigDecimal.
They also support a min and a max value.
Maybe you find them useful (the library is open source):
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
Tutorial:
http://softsmithy.sourceforge.net/lib/docs/tutorial/swing/number/index.html
Homepage:
http://www.softsmithy.org
Download:
http://sourceforge.net/projects/softsmithy/files/softsmithy/
Maven:
<dependency>
<groupid>org.softsmithy.lib</groupid>
<artifactid>lib-core</artifactid>
<version>0.1</version>
</dependency>
-Puce
精彩评论