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中格式化文本/幫助/指南焦點丟失後,格式會根據輸入的位數而變化。
那麼當你的格式文本字段中再次獲得焦點:將它需要改變它的文本格式的形式'123-456- 7890'到'1234567890'?有線選項要求! – Sage
無論如何看看答案。看看它是否有助於滿足您的要求 – Sage