限制Java中的文本字段 [英] Limiting Textfields in Java

查看:107
本文介绍了限制Java中的文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将文本字段限制为只允许数字0-100,从而排除字母,符号等?我找到了一种方法,但它似乎比看起来更复杂。

Is there a way to limit a textfield to only allow numbers 0-100, thereby excluding letters, symbols and such as well? I have found a way, but it is way more complicated than seems necessary.

推荐答案

如果你必须使用文本字段,你应该使用 JFormattedTextField 并使用 NumberFormatter 。您可以设置NumberFormatter上允许的最小值和最大值。

If you must use a text field you should use a JFormattedTextField with a NumberFormatter. You can set the minimum and maximum values allowed on the NumberFormatter.

NumberFormatter nf = new NumberFormatter();
nf.setValueClass(Integer.class);
nf.setMinimum(new Integer(0));
nf.setMaximum(new Integer(100));

JFormattedTextField field = new JFormattedTextField(nf);

但是,如果适合您的使用案例,Johannes建议使用JSpinner也是合适的。

However, Johannes suggestion of using a JSpinner is also appropriate if it suits your use case.

这篇关于限制Java中的文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆