views:

141

answers:

1

I'm using BigDecimal to represent product prices in a Java SE application.

What swing component(s) should I use in order to allow the user to input numbers with only two decimal places and bound it to a BigDecimal variable/Object's property. (Checking that as the user types)?

I've been playing with JTextField, JFormattedTextField, NumberFormatter, MaskFormatter but I can't work it out.

Is there any combination and configuration of those components to do that? or should I extend the MaskFormatter, the JTextField, ...?

+1  A: 

I'm not quite sure what you are trying to do, but there is a BigDecimal constructor which takes Strings as parameter (similar to e.g. Double.parseDouble(String s)):

try
{
    BigDecimal decimal = new BigDecimal(yourJTextField.getText());
}
catch (NumberFormatException nfe)
{ /* error handling */}

See JavaDoc for BigDecimal for more information.

Edit: If checking/validating the user's input into the textfield, either check it manually or use a Validator (see Google results for "JTextField Validator")

Tedil
The problems is that I want a component that only allows numbers, and only allows 2 decimal places on it: if the user types a letter, it's not shown, if the user types a third decimal place, it's not shown. On top of that I want to bound that component to a BigDecimal variable.
Toto
Have a look at the InputVerifier doc then: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/InputVerifier.html
Tedil
The InputVerifier acts when the focus changes. I want to control the input as the user types in the component.
Toto
You could, of course, simply use the CaretPositionChanged Event for TextFields, check what the user has entered, if it's valid, don't do anything, if it's invalid remove the last typed character.
Tedil