[RESOLVIDO]setText Limpando JTextField ao usar do PlainDocument

6 respostas
wilsontads

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:

6 Respostas

ViniGodoy

Sem postar o PlainDocument que você está usando, fica bem difícil te ajudar.

wilsontads
Desculpe..
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);
            
        }

    }
}
wilsontads

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.

wilsontads

Debugando aqui, cheguei à seguinte mensagem:

For input string: "[telefone removido]"
ViniGodoy

Esse valor é superior ao máximo que o Integer suporta ([telefone removido]).

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.

wilsontads

Valeu, baixei a biblioteca commons-lang3-3.1.jar que tem o isNumeric e resolveu aqui… ObG:

Criado 19 de fevereiro de 2012
Ultima resposta 19 de fev. de 2012
Respostas 6
Participantes 2