How to set jFormattedTextField so it only allows 2 numbers?

醉酒当歌 提交于 2019-11-30 05:26:17

问题


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 JFormattedTExtFields and I don't know how to customize the allowed input in them. Basically I'm trying to find out how to:

  • Only allow numbers to be entered in JFormmatedTextField;
  • Only allow a certain amount of numbers;

回答1:


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());


来源:https://stackoverflow.com/questions/8637792/how-to-set-jformattedtextfield-so-it-only-allows-2-numbers

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