2010-09-21 38 views
0

我使用的JFormattedTextField的電話號碼和只接受數值我問題NumberFormatted廠在Java中擺動

宣佈其爲「新NumberFormatterFactory(Integer.class,FALSE)」。

現在的問題是,當數字以0(零)開始時,如001345 ..,輸入值並移動到下一列後,輸入值被修整爲1345 ..在這裏它不接受0作爲起始數字。

我怎麼能輸入數字與0

+1

001345是一樣的1345如果你有興趣在零位,你是不是在找數(整數),但您可能只會查找帶有數字字符的字符串。 – Thirler 2010-09-21 07:37:27

+0

如果你聲明它爲整數0不會被考慮。 – YoK 2010-09-21 07:38:38

回答

0

呀,電話號碼都是從這個意義上整數略有不同。

this example你可以使用正則表達式這樣就解決了:

import java.text.ParseException; 
import java.util.regex.*; 

import javax.swing.*; 
import javax.swing.text.DefaultFormatter; 

class RegexFormatter extends DefaultFormatter { 
    private Pattern pattern; 

    private Matcher matcher; 

    public RegexFormatter() { 
     super(); 
    } 

    public RegexFormatter(String pattern) throws PatternSyntaxException { 
     this(); 
     setPattern(Pattern.compile(pattern)); 
    } 

    public RegexFormatter(Pattern pattern) { 
     this(); 
     setPattern(pattern); 
    } 

    public void setPattern(Pattern pattern) { 
     this.pattern = pattern; 
    } 

    public Pattern getPattern() { 
     return pattern; 
    } 

    protected void setMatcher(Matcher matcher) { 
     this.matcher = matcher; 
    } 

    protected Matcher getMatcher() { 
     return matcher; 
    } 

    public Object stringToValue(String text) throws ParseException { 
     Pattern pattern = getPattern(); 

     if (pattern != null) { 
      Matcher matcher = pattern.matcher(text); 

      if (matcher.matches()) { 
       setMatcher(matcher); 
       return super.stringToValue(text); 
      } 
      throw new ParseException("Pattern did not match", 0); 
     } 
     return text; 
    } 
} 


public class Test { 
    public static void main(String[] a) { 
     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     JFormattedTextField formattedField = 
       new JFormattedTextField(new RegexFormatter("\\d*")); 
     frame.add(formattedField, "North"); 
     frame.add(new JTextField(), "South"); 
     frame.setSize(300, 200); 
     frame.setVisible(true); 
    } 
}