Fla galera! Bom, o tópico é meio antigo, mas vou deixar uma ajuda caso alguem pergunte ao prof. google rs…
Seguinte, ao especializar a classe PlainDocument, temos um problema quando usamos o BeansBinding, pois ele usa o Document do próprio binding. Implementei as duas classes abaixo, que podem ser alteradas de acordo com a necessidade, especializando a classe DocumentFilter (descobri isso através de pesquisas, as quais tem as referências no fim da msg). Ao setar este document em um JTextField é necessário fazer um cast. Segue o código:
/*
* Esta classe limita o número de caracteres inseridos em um JTextField
* Para usar este Document: ((AbstractDocument)jTextField.getDocuement()).setDocumentFilter(new FixedLengthDocument(5));
*/
package util;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
/**
*
* @author Paulo Alonso
*/
public class FixedLenghtDocument extends DocumentFilter {
private int iMaxLength;
public FixedLenghtDocument(int maxlen) {
super();
iMaxLength = maxlen;
}
@Override
public void insertString(FilterBypass fb, int offset, String str, AttributeSet attr) throws BadLocationException {
if (str == null) return;
// aceitara qualquer número de caracteres
if (iMaxLength <= 0) {
fb.insertString(offset, str, attr);
return;
}
int ilen = (fb.getDocument().getLength() + str.length());
// se o comprimento final for menor, aceita str
if (ilen <= iMaxLength) {
fb.insertString(offset, str, attr);
} else {
// se o comprimento for igual ao máximo, não faz nada
if (fb.getDocument().getLength() == iMaxLength) return;
// se ainda resta espaço na String, pega os caracteres aceitos
String newStr = str.substring(0, (iMaxLength - fb.getDocument().getLength()));
fb.insertString(offset, newStr, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String str, AttributeSet attr) throws BadLocationException {
if (str == null) return;
// aceitara qualquer número de caracteres
if (iMaxLength <= 0) {
fb.insertString(offset, str, attr);
return;
}
int ilen = (fb.getDocument().getLength() + str.length());
// se o comprimento final for menor, aceita str
if (ilen <= iMaxLength) {
fb.insertString(offset, str, attr);
} else {
// se o comprimento for igual ao máximo, não faz nada
if (fb.getDocument().getLength() == iMaxLength) return;
// se ainda resta espaço na String, pega os caracteres aceitos
String newStr = str.substring(0, (iMaxLength - fb.getDocument().getLength()));
fb.insertString(offset, newStr, attr);
}
}
}
Obs.: Não entendi bem a diferença entre insertString() e replace(), deixei os dois iguais e funcionou, se alguém souber, posta aí
Esta classe especializa FixedLenghtDocument e permite somente números e pontos, além de limitar o número de caracteres
/*
* Esta classe permite que apenas números sejam inseridos em um JTextField
* Para usar este Document: ((AbstractDocuement) jTextField.getDocument()).setDocumentFilter(new IntegerDocument());
*/
package util;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
/**
*
* @author Paulo Alonso
*/
public class IeValidator extends FixedLenghtDocument {
public IeValidator(int maxLenght) {
super(maxLenght);
}
@Override
public void insertString(FilterBypass fb, int offset, String str, AttributeSet attr) throws BadLocationException {
char c;
byte n = 1;
// percorre a string
for (byte i=0;i<str.length();i++){
// armazena o caracter
c = str.charAt(i);
// se não for número ou ponto
if(!Character.isDigit(c) & c != '.')
n = 0;
}
// se n não for igual a zero, todos os caracteres são numéricos
if(n != 0)
super.insertString(fb, offset, str, attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String str, AttributeSet attr) throws BadLocationException {
char c;
byte n = 1;
// percorre a string
for (byte i=0;i<str.length();i++){
// armazena o caracter
c = str.charAt(i);
// se não for número ou ponto
if(!Character.isDigit(c) & c != '.')
n = 0;
}
// se n não for igual a zero, todos os caracteres são numéricos
if(n != 0)
super.insertString(fb, offset, str, attr);
}
}
Aplicação
((AbstractDocument) txtIe.getDocument()).setDocumentFilter(new util.IeValidator(5));
Referências
http://www.guj.com.br/java/127759-maxlenght–jtextfield–swing–beansbinding
http://www.java2s.com/Code/JavaAPI/javax.swing.text/AbstractDocumentsetDocumentFilterDocumentFilterfilter.htm
Abraço!