如何设置jFormattedTextField所以它只允许2个数字? [英] How to set jFormattedTextField so it only allows 2 numbers?
问题描述
我是Java和NetBeans的初学者。我正在尝试制作一个简单的程序,你引入2个数字,它们的总和除以2。但是,我正在使用 JFormattedTExtField
,我不知道如何自定义其中允许的输入。基本上我正试图找出如何:
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 JFormattedTExtField
s and I don't know how to customize the allowed input in them. Basically I'm trying to find out how to:
- 只允许在
JFormmatedTextField $中输入数字c $ c>;
- 只允许一定数量的数字;
推荐答案
您可以使用NumberFormat并使用 setMaximumIntegerDigits 。
You could use a NumberFormat and specify the maximum number of integer digits with setMaximumIntegerDigits.
这是一个不错的文章。
基本上你可以这样做:
NumberFormat f = NumberFormat.getNumberInstance();
f.setMaximumIntegerDigits(maxDigitsAmount);
JFormattedTextField field = new JFormattedTextField(f);
格式应保证插入的String满足格式。无论如何,即使提供了数字,文本字段也会将其存储为字符串。因此,如果您需要原始的Integer,则需要像建议的@noise一样重建它:
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());
这篇关于如何设置jFormattedTextField所以它只允许2个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!