How to set jFormattedTextField so it only allows 2 numbers?

前端 未结 1 778
情深已故
情深已故 2021-01-05 22:01

I\'m a beginner in Java, and NetBeans. I\'m trying to make a simple program where you introduce 2 numbers and their sum gets divided by two. However, I\'m using JForma

相关标签:
1条回答
  • 2021-01-05 22:40

    You could use a NumberFormat and specify the maximum number of integer digits with setMaximumIntegerDigits.

    Here's a nice article.

    Basically you can do something like:

    NumberFormat f = NumberFormat.getNumberInstance(); 
    f.setMaximumIntegerDigits(maxDigitsAmount);
    JFormattedTextField field = new JFormattedTextField(f);
    

    The Format should guarantee that the inserted String satisfy the format. Anyway even if a number is supplied, the textfield will store it as a String. So if you need your original Integer you need to rebuild it like suggested @noise:

    Integer i = Integer.toString(field.getText());
    
    0 讨论(0)
提交回复
热议问题