如何在JTextField中禁止特殊字符 [英] How to disallow special characters in JTextField
问题描述
我正在尝试在 JTextField
中禁止使用特殊字符.这是针对我需要进行表单验证的项目.目前,我只能允许数字,但不能禁止特殊字符,例如 @
或#
或/
或 \
.这是我到目前为止所做的.
I am trying to disallow special characters in JTextField
. This is for a project where I need to do form validation. At the moment I can only allow numbers but I cannot disallow special characters such as @
or #
or /
or \
. Below is what I have made so far.
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
int i= Integer.parseInt(jTextField2.getText());
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Please enter Int Value", "Invail Input", JOptionPane.ERROR_MESSAGE);
}
}
推荐答案
我认为,您可以使用 JFormattedTextField
,而不是添加侦听器并仅使用简单的 JTextField
.正如Oracle文档所述:
I think, instead of adding listeners and using just a simple JTextField
, you can use JFormattedTextField
. As it is said in Oracle docs:
JFormattedTextField-一个JTextField子类,允许您指定用户可以输入的合法字符集.
JFormattedTextField - A JTextField subclass that allows you to specify the legal set of characters that the user can enter.
检查以下链接:
这篇关于如何在JTextField中禁止特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!