【发布时间】:2012-11-13 04:00:03
【问题描述】:
我在 JFrame 中有 2 个文本字段,当焦点从 textfield1 丢失时,我想验证 textfield1 中的数据。所以我在FocusLost() 方法中使用了FocusListener 和showMessageDialog(),然后将焦点重新设置回textfield1。当我单击除 textfield1 之外的 JFrame 窗口内的任何组件时,它工作正常,但是当我单击 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;
}
}
【问题讨论】:
-
您应该为此使用
InputVerifier,这就是它的设计目的。以Validating Input 为例。听起来您不止一次将焦点侦听器附加到该字段。 -
鉴于
show属性的使用,更合乎逻辑的标题是shown(过去时)或hide。 -
使用 DocumentFilter,大多数 Swing Listeners 被触发了两次
-
如果您想要
JTextField进行验证,请使用JFormattedTextField -
只是一个让代码更干净的提示。我会选择:!show 而不是 show==false。
标签: java swing validation