Pessoal, to com um probleminha aqui… utilizei o PlainDocument, mostrado em um exemplo aqui no fórum para deixar os caracteres todos em maiusculos. Funcionou perfeitamente, o problema que estou tendo é que, quando faço algo do tipo :
tfCpfCnpj.setText("Wilson M.");
Meu TextField é limpado, e a mensagem contida no setText não aparece.
Alguém aqui já teve um problema semelhante, e pode ajudaR?
Att:
Sem postar o PlainDocument que você está usando, fica bem difícil te ajudar.
Desculpe…
[code]import java.awt.Toolkit;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class TextFieldMaskCpf extends PlainDocument {
private int iMaxLength = 14;
@Override
public void insertString(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (iMaxLength <= 0) // aceitara qualquer no. de caracteres
{
try {
Integer.parseInt(str);
super.insertString(offset, str, attr);
formatCpf(offset, attr);
return;
} catch (NumberFormatException e) {
Toolkit.getDefaultToolkit().beep();
return;
}
}
int ilen = (getLength() + str.length());
if (ilen <= iMaxLength) // se o comprimento final for menor...
{
try {
Integer.parseInt(str);
super.insertString(offset, str, attr); // ...aceita str
formatCpf(offset, attr);
} catch (NumberFormatException e) {
Toolkit.getDefaultToolkit().beep();
}
}
}
private void formatCpf(int offset, AttributeSet attr)
throws BadLocationException {
if (getLength() == 4) {
super.insertString(offset, ".", attr);
} else if (getLength() == 8) {
super.insertString(offset, ".", attr);
} else if (getLength() == 12) {
super.insertString(offset, "-", attr);
}
}
}[/code]
Na verdade fiz uma confusão de idéias, a intenção é mascarar o campo de CPF usando o PlainDocument ao invés do JFormattedTextField e não colocar tudo em UpperCase.
Debugando aqui, cheguei à seguinte mensagem:
For input string: "12345678900"
Esse valor é superior ao máximo que o Integer suporta (2147483647).
Trabalhe diretamente com Strings ou use um long. Mas seria bom validar se o texto digitado tem mais dígitos que um CPF antes de fazer o parse.
Valeu, baixei a biblioteca commons-lang3-3.1.jar que tem o isNumeric e resolveu aqui… ObG: