How to use BigDecimal in swing GUIs?

大憨熊 提交于 2019-12-11 10:54:12

问题


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:


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




回答2:


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



来源:https://stackoverflow.com/questions/2495456/how-to-use-bigdecimal-in-swing-guis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!