我有一个 JFormattedTextField
我只想在其中插入字母数字字符。当用户键入不允许的字符时,我尝试使用此代码启动 JDialog
,并且万一一切正常,可以从 JFormattedTextField
获取字符串。当我运行此代码时,当我键入符号时不会出现 JOptionPane
。我知道我的代码有问题,但由于我的经验很少,我无法识别它。我希望得到一些帮助。
提前谢谢
static JFormattedTextField indivname = new JFormattedTextField();
final String individ = indivname.getText();
indivname.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn(individ);
}
public void removeUpdate(DocumentEvent e) {
warn(individ);
}
public void insertUpdate(DocumentEvent e) {
warn(individ);
}
public void warn(String textcheck) {
textcheck = indivname.getText();
boolean match = textcheck.matches("[a-zA-Z0-9]+");
if (match=false) {
JOptionPane.showMessageDialog(null, "You have inserted restricted characters (Only alphanumeric characters are allowed)", "Warning", JOptionPane.WARNING_MESSAGE);
}
if (match=true) {
textcheck = individ ;
}
}
});
最佳答案
您在 if
语句中使用赋值运算符 =
而不是比较 ==
:
if (match = false) {
...
if (match=true) {
表达式 match = false
导致 match
获取 false
值,并且整个表达式始终返回 false
.
您应该将其替换为:
if (!match) {
JOptionPane.showMessageDialog(null, "You have inserted restricted characters (Only alphanumeric characters are allowed)", "Warning", JOptionPane.WARNING_MESSAGE);
} else { // instead of if(match)
textcheck = individ;
}
它直接使用match
的值来确定要执行哪个分支。
关于java - 检查 JTextField 是否仅包含特定允许的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22327203/