quinta-feira, 19 de março de 2009

Mascara para IP (com ER)

Estava eu procurando uma forma de criar uma mascara em um jtextfield, para certificar que o usuário digitou um IP válido. Depois de muita procura no google, encontrei um exemplo que utiliza expressões regulares para testar o valor digitado pelo usuário.
Para isso coloque um jFormattedTextfield em um jFrame qualquer crie a seguinte classe:

import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.swing.text.DefaultFormatter;

/**
*
* @author homisinho
*/
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;
}

@Override
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;
}

}


E coloque o seguinte código em seu jFrame para utilizar a expressão regular:

///expressão regular para controlar o IP valido
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);
txtip.setFormatterFactory(new DefaultFormatterFactory(ipFormatter));
/////////////////////////////////////////


No lugar de “txtip” coloque o nome do seu jFormattedTextfield. Encontrei esse exemplo no site http://www.gamedev.net, caso tenha dúvidas com expressões regulares de uma procurada no google.

Nenhum comentário: