Original Post
First of all, this is what I've come up with for having a JFormattedTextField validate an IP address. Someday, this may help someone, and since I went through the trouble of getting it working, I'm sharing the fun :) This is a RegexFormatter I found on the java website: Regular Expression Based AbstractFormatter Here is an example of using the class with a regular expression... I was wondering if someone could explain to me how the expression works. I don't like not understanding stuff like this. I googled for regex tutorials, but they didn't help me much. String _255 = "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"; Pattern p = Pattern.compile( "^(?:" + _255 + "\\.){3}" + _255 + "$");
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.swing.text.DefaultFormatter;
public 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;
}
}
String _255 = "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
Pattern p = Pattern.compile( "^(?:" + _255 + "\\.){3}" + _255 + "$");
RegexFormatter ipFormatter = new RegexFormatter( p );
JFormattedTextField ipAddress = new JFormattedTextField( ipFormatter );
ipAddress.addPropertyChangeListener( "value",
new PropertyChangeListener() {
public void propertyChange( PropertyChangeEvent e ) {
System.out.println( ipAddress.getValue() );
}
}
);