开发者

How to use BigDecimal in swing GUIs?

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

What swing componen开发者_如何学Pythont(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, ...?


I hate to necro these really old threads on stuff, but my understanding is StackOverflow cries inside every day an answer remains unsolved.

so you can checkout the code here: http://www.java2s.com/Code/Java/Swing-JFC/ABigDecimalobjectcustomformatter.htm

basically set-up to a JFormattedTextField to use a DecimalFormat


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")

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜