problem with NumberFormatted Factory in Java swings
I use a jFormattedTextField for a telephone number and only to acc开发者_StackOverflow社区ept the numeric values i
declare it as "new NumberFormatterFactory(Integer.class, false)" .
Now the problem is when the number starts with 0(zero) like 001345.. , after entered the value and moved to next column the entered value is trimmed as 1345.. here it not accepting the 0 as the starting number.
how can I enter the number starts with 0
Yeah, telephone numbers are slightly different from integers in that sense.
Following this example at you could solve it using regular expressions like this:
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);
}
}
If you declare it as new NumberFormatterFactory(Integer.class, false)
which is for only Integer
, 0
wont be considered. You need to change it to other formatter and not store Phone Number as number (i.e. Integer).
Check this example for phone number formatting:
http://www.java2s.com/Code/Java/Swing-JFC/JFormattedTextFieldaninputmaskforatelephonenumber.htm
http://www.ibm.com/developerworks/java/library/j-mer0625/index.html
精彩评论