Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package mage.form.doc;
- import java.util.regex.*;
- import javax.swing.text.*;
- /**
- * Document personalizado que cria um mascara para insercao de CPF (Brasil)
- *
- * @author Arthur Gregorio
- * @version 1.0, 25/04/2011
- * @since 1.0
- */
- public class CPFDocument extends PlainDocument {
- private Pattern regex = Pattern.compile("[0-9]");
- /**
- * Sobrescrita do metodo de insercao de dados no TextComponent
- *
- * @see PlainDocument#insertString(int, java.lang.String,
- * javax.swing.text.AttributeSet)
- *
- * @param offs
- * @param str
- * @param a
- *
- * @throws BadLocationException
- */
- @Override
- public void insertString(int offs, String str, AttributeSet a)
- throws BadLocationException {
- try {
- str = formatter(str);
- if (str.isEmpty()) return;
- String inserido = getText(0, getLength());
- if(inserido.length() < 14) {
- remove(0, getLength());
- StringBuilder sb = new StringBuilder();
- sb.append(inserido.replaceAll("[^\\w]", ""));
- sb.append(str);
- if(sb.length() < 3) {
- sb.insert(0, "-");
- } else {
- sb.insert(sb.length()-2, "-");
- }
- if(sb.length() >= 7) {
- sb.insert(sb.length()-6, ".");
- }
- if(sb.length() >= 11) {
- sb.insert(sb.length()-10, ".");
- }
- super.insertString(0, sb.toString(), a);
- }
- } catch(Exception ex) {
- System.err.println(ex.getMessage());
- }
- }
- /**
- * Criacao do formatador que aceitara apenas numeros
- *
- * @param string a String a ser validada
- *
- * @return a String validada
- */
- private String formatter(String string) {
- Matcher matcher = regex.matcher(string);
- StringBuilder sb = new StringBuilder();
- while (matcher.find()) {
- sb.append(matcher.group());
- }
- return sb.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment