JFrame中有两个textfield1,当焦点从textfield1中丢失时,我希望验证textfield1中的数据。因此,我在FocusListener方法中使用了showMessageDialog()和showMessageDialog(),然后将焦点返回到textfield1。当我单击JFrame窗口中的除textfield1之外的任何组件时,它工作得很好,但是当我单击JFrame窗口之外的任何位置时,showMessageDialog()会被调用两次,而焦点则会转到textfield2,而焦点应该保持在textfield1上。
@Override
public void focusGained(FocusEvent e) {}
@Override
public void focusLost(FocusEvent e) {
boolean show = false;
String theRegex = "[0-9]";
Pattern checkRegex = Pattern.compile(theRegex);
Matcher regexMatcher = checkRegex.matcher( MemberID );
while ( !regexMatcher.find() && show==false){
JOptionPane.showMessageDialog(null,"Please enter numbers","Validation Error",JOptionPane.ERROR_MESSAGE);
MemberID_Text.requestFocusInWindow();
MemberID_Text.selectAll();
show = true;
}
}发布于 2012-11-13 13:54:09
您可以这样做,以验证是否输入了一个数字,并避免所有的正则表达式在一起。
class IntVerifier extends InputVerifier {
@Override public boolean verify(JComponent input) {
String text =((JTextField) input).getText();
int n = 0;
try {
n = Integer.parseInt(text); }
catch (NumberFormatException e) {
return false;
}
return true;
}
}然后在文本字段上使用输入验证器。
IntVerifier intv = new IntVerifier();
myTextField = new JTextField();
myTextField.setInputVerifier(intv);https://stackoverflow.com/questions/13355398
复制相似问题