根据条件格式化焦点丢失的文本字段

时间:2013-10-11 18:56:44

标签: java swing formatting jformattedtextfield

这就是我需要的:用户可以输入的文本字段:

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中的文本,格式因输入的位数而异。

1 个答案:

答案 0 :(得分:0)

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

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

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

ftfJFormattedTextFeild。尝试将input verifier分配给formatted text field,以便检查并验证焦点丢失事件的文本。 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);
  }
}