0

这是我需要的:一个文本字段,用户可以在其中输入:

1234567890 或 11234567890

并且需要相应地格式化为

123-456-7890 或 1 123-456-7890

本质上是一个带有或不带有国家代码的电话号码。到目前为止,我有一个执行以下操作的代码:

if (isPhone && !getText().equals(BLANK_STRING)) {
        int phoneLength = getText().replaceAll("[^0-9]", "").length();
        String text = getText().replaceAll("[^0-9]", "");
//We call the method to format the entered text after we left the field
        setPhoneFormatMask(phoneLength, text); 
}

private void setPhoneFormatMask(int length, String text) {
    System.out.println("length = " + length);
    System.out.println("text = " + text);
    switch (length) {
        case 10:
            try {
                System.out.println("Setting mask");
                numberMaskFormat.setMask("###-###-####");
            } catch (ParseException ex) {
                Logger.getLogger(WWNumericFormattedTextField.class.getName()).log(Level.SEVERE, null, ex);
            }
            break;
        case 11:
            try {
                System.out.println("setting mask 2");
                numberMaskFormat.setMask("# ###-###-####");
            } catch (ParseException ex) {
                Logger.getLogger(WWNumericFormattedTextField.class.getName()).log(Level.SEVERE, null, ex);
            }
            break;
    }
    setFormatter(numberMaskFormat);
    System.out.println("n:" + numberMaskFormat.getMask());
    setText(text);
}

@Override
public void focusGained(FocusEvent e) {
    if (isPhone) {
        try {
            numberMaskFormat.setMask("**************");
        } catch (ParseException ex) {
            Logger.getLogger(WWFormattedTextField.class.getName()).log(Level.SEVERE, null, ex);
        }
        setFormatter(numberMaskFormat);
    }
}

控制台输出:

//Application launched
focus gained
n2:**************
//I entered 9051234567 and tabbed out
Focus lost
length = 10
text = 9051234657
Setting mask
n:###-###-####
Formatted text =    -   -    
//Tabbed back in
focus gained
n2:**************
//Entered 19051234567 and tabbed out
Focus lost
length = 11
text = 19051234567
setting mask 2
n:# ###-###-####
Formatted text = 

我需要关于如何在焦点丢失后格式化 JFormattedTextField 中的文本的建议/帮助/指导,并且格式会根据输入的数字而有所不同。

4

1 回答 1

0

首先,使用掩码:#对于任何有效数字,使用 Character.isDigit 因为*适用于任何字符。

其次DefaultFormatterFactory在将格式化程序设置为时使用JFormattedTextFeild

    ftf.setFormatterFactory(new DefaultFormatterFactory(
                                                new MaskFormatter("######"))); 

ftf是一个JFormattedTextFeild。尝试分配一个input verifierto formatted text fielddo 检查和验证焦点丢失事件的文本。将在焦点丢失事件上InputVarifier调用一个函数boolean shouldYieldFocus(JComponent input)来检查它应该在哪里丢失焦点。我已经为您编写了一个示例示例,您可以轻松地采用它来满足您的需要:

 class myInputVarifier extends InputVerifier
{
  public boolean maskChanged = false;
  MaskFormatter maskFormatter ;
  JFormattedTextField ftf;
  @Override
  public boolean verify(JComponent input) {
    if (input instanceof JFormattedTextField) {
             ftf = (JFormattedTextField)input;
             maskFormatter = (MaskFormatter) ftf.getFormatter();
             ;
             if(!isValid()) return false; 
                           // check with mask ###### first, if valid change the mask
                           // to # ##-### and reset the text 

             if(!maskChanged)
             {
               try {
                    String text = ftf.getText();  
                           // get the text formatted as ###### = 112123
                     maskFormatter.setMask("# ##-###");
                     ftf.setFormatterFactory(
                                           new DefaultFormatterFactory(maskFormatter));
                     ftf.setText(text);
                          //resetting the text will be formatted as # ##-### = 1 12-123
                     maskChanged = true;
               } catch (ParseException ex) {
                   }

               return isValid();
             }


          }
          return true;
  }

  public boolean isValid()
  {
        try {
           maskFormatter.stringToValue(ftf.getText());
           return true;
         } catch (ParseException pe) {
             return false;
           }
   }

  @Override
  public boolean shouldYieldFocus(JComponent input) {
    return verify(input);
  }
}   
于 2013-10-11T21:04:18.127 回答