arthurgregorio

CPFDocument

Nov 16th, 2013
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.17 KB | None | 0 0
  1. package mage.form.doc;
  2.  
  3. import java.util.regex.*;
  4. import javax.swing.text.*;
  5.  
  6. /**
  7.  * Document personalizado que cria um mascara para insercao de CPF (Brasil)
  8.  *
  9.  * @author Arthur Gregorio
  10.  * @version 1.0, 25/04/2011
  11.  * @since 1.0
  12.  */
  13. public class CPFDocument extends PlainDocument {
  14.  
  15.     private Pattern regex = Pattern.compile("[0-9]");
  16.  
  17.     /**
  18.      * Sobrescrita do metodo de insercao de dados no TextComponent
  19.      *
  20.      * @see PlainDocument#insertString(int, java.lang.String,
  21.      *      javax.swing.text.AttributeSet)
  22.      *
  23.      * @param offs
  24.      * @param str
  25.      * @param a
  26.      *
  27.      * @throws BadLocationException
  28.      */
  29.     @Override
  30.     public void insertString(int offs, String str, AttributeSet a)
  31.             throws BadLocationException {
  32.  
  33.         try {
  34.             str = formatter(str);
  35.  
  36.             if (str.isEmpty()) return;
  37.  
  38.             String inserido = getText(0, getLength());
  39.  
  40.             if(inserido.length() < 14) {
  41.                 remove(0, getLength());
  42.  
  43.                 StringBuilder sb = new StringBuilder();
  44.  
  45.                 sb.append(inserido.replaceAll("[^\\w]", ""));
  46.                 sb.append(str);
  47.  
  48.                 if(sb.length() < 3) {
  49.                     sb.insert(0, "-");
  50.                 } else {
  51.                     sb.insert(sb.length()-2, "-");
  52.                 }
  53.  
  54.                 if(sb.length() >= 7) {
  55.                     sb.insert(sb.length()-6, ".");
  56.                 }
  57.  
  58.                 if(sb.length() >= 11) {
  59.                     sb.insert(sb.length()-10, ".");
  60.                 }
  61.  
  62.                 super.insertString(0, sb.toString(), a);
  63.             }
  64.         } catch(Exception ex) {
  65.             System.err.println(ex.getMessage());
  66.         }
  67.     }
  68.  
  69.     /**
  70.      * Criacao do formatador que aceitara apenas numeros
  71.      *
  72.      * @param string a String a ser validada
  73.      *
  74.      * @return a String validada
  75.      */
  76.     private String formatter(String string) {
  77.  
  78.         Matcher matcher = regex.matcher(string);
  79.         StringBuilder sb = new StringBuilder();
  80.  
  81.         while (matcher.find()) {
  82.             sb.append(matcher.group());
  83.         }
  84.  
  85.         return sb.toString();
  86.     }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment