我使用的JFormattedTextField的電話號碼和只接受數值我問題NumberFormatted廠在Java中擺動
宣佈其爲「新NumberFormatterFactory(Integer.class,FALSE)」。
現在的問題是,當數字以0(零)開始時,如001345 ..,輸入值並移動到下一列後,輸入值被修整爲1345 ..在這裏它不接受0作爲起始數字。
我怎麼能輸入數字與0
我使用的JFormattedTextField的電話號碼和只接受數值我問題NumberFormatted廠在Java中擺動
宣佈其爲「新NumberFormatterFactory(Integer.class,FALSE)」。
現在的問題是,當數字以0(零)開始時,如001345 ..,輸入值並移動到下一列後,輸入值被修整爲1345 ..在這裏它不接受0作爲起始數字。
我怎麼能輸入數字與0
開始如果你聲明爲new NumberFormatterFactory(Integer.class, false)
這是唯一Integer
,0
不會予以考慮。您需要將其更改爲其他格式化程序,而不要將電話號碼存儲爲號碼(即整數)。
檢查這個例子電話號碼格式:
http://www.java2s.com/Code/Java/Swing-JFC/JFormattedTextFieldaninputmaskforatelephonenumber.htm
http://www.ibm.com/developerworks/java/library/j-mer0625/index.html
呀,電話號碼都是從這個意義上整數略有不同。
繼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);
}
}
001345是一樣的1345如果你有興趣在零位,你是不是在找數(整數),但您可能只會查找帶有數字字符的字符串。 – Thirler 2010-09-21 07:37:27
如果你聲明它爲整數0不會被考慮。 – YoK 2010-09-21 07:38:38