0

I want to know what's wrong with this code? I am taking my input in the textbox(A 10-digit mobile number). My problem is that, this code all the time prints else statement even if my input is correct.

mobNo=textMobNo.getText();

textMobNo.addFocusListener(new FocusListener() {

    @Override
    public void focusLost(FocusEvent arg0) {
        // TODO Auto-generated method stub

        Pattern pattern = Pattern.compile("^[789]\\d{9}$");
        Matcher matcher = pattern.matcher(mobNo);

        if (matcher.matches()){
            System.out.println("valid");
        }
        else{
            System.out.println("invalid");
        }       
    }

    @Override
    public void focusGained(FocusEvent arg0) {
        // TODO Auto-generated method stub

    };
});
4

1 回答 1

1

您正在从文本字段中获取文本,然后添加一个 focusListener。在稍后的某个时间,焦点侦听器被触发,然后它使用您在焦点侦听器处于活动状态之前从您的字段中获得的文本。是的,该文本可能来自在该字段中输入任何内容之前;这将解释它是一个空字符串。尝试在焦点侦听器中获取文本...(提示 - 您从文本字段中获取的字符串不会随着在字段中键入文本而不断更新...)

于 2013-09-04T16:34:13.153 回答