Restringir Caracteres

6 respostas
Z
Olá amigos, estou com dificuldades nesse codigo para limitar o jtextfiled em 4 o numero de caracteres possiveis dentro dele... estou usando o NetBeans alguem sabe pq nao esta funcionando...ele nao da erro....ela apenas nao permite a escrita dentro dele de nenhum caracter....pq sera?
private void CodigoKeyTyped(java.awt.event.KeyEvent evt) {                                
 // TODO adicione seu código de manipulação aqui:
         int k = evt.getKeyChar();
           if((k > 0 && k < 5)) {
               if(Codigo.getText().length() == 4){
                   evt.setKeyChar((char)KeyEvent.VK_CLEAR);
               }
           } else {
               evt.setKeyChar((char)KeyEvent.VK_CLEAR);
           }
 
     }

6 Respostas

B

Ola,
Eu te aconselharia a usar as facilidades do Document, tem até um exemplo de como fazer para só aparecer caracteres em maiusculos no textfield… dá uma olhada na API dele que tem lá.

S

Boa dica,

Agora aproveitando o assunto, eu tive um problema similar, só que eu queria restringir letras e permitir só números, mas o caractere digitado é inserido depois que o evento é executado, logo eu fazia algo parecido como do amigo aí em cima, mas acabava retirando o caractere que já estava, exemplo:

Inicio: “01234”
Digitei a letra “J”
Ficará: “0123J”

Quando digito, o evt reconhece que é “J”, mas no TextField não existe o J ainda, entao ele apaga antes, e ainda por cima insere o J pois não consigo evitar que ele o coloque.

Alguma luz? :idea:

B

Ola,

Buscando aqui no google, achei estas aqui, um bom material pra vcs…
http://www.google.com.br/search?q=plaindocument+java%2Bnumber+only&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:pt-BR:official&client=firefox-a

e uma em especial:
http://java.sun.com/developer/JDCTechTips/2005/tt0518.html

S

Muito bom Bruno! Deu certo

Se souber me dizer… quem dispara os métodos dessa classe? Como sei os nomes que elas devem ter?

zzzhhh, use este:

import javax.swing.text.*;

   public class IntegerDocument extends PlainDocument {

     int currentValue = 0;

     public IntegerDocument() {
     }

     public int getValue() {
       return currentValue;
     }

     public void insertString(int offset, String string,
         AttributeSet attributes) throws BadLocationException {

       if (string == null) {
         return;
       } else {
         String newValue;
         int length = getLength();
         if (length == 0) {
           newValue = string;
         } else {
           String currentContent = getText(0, length);
           StringBuffer currentBuffer = 
                new StringBuffer(currentContent);
           currentBuffer.insert(offset, string);
           newValue = currentBuffer.toString();
         }
         currentValue = checkInput(newValue, offset);
         super.insertString(offset, string, attributes);
       }
     }
     public void remove(int offset, int length)
         throws BadLocationException {
       int currentLength = getLength();
       String currentContent = getText(0, currentLength);
       String before = currentContent.substring(0, offset);
       String after = currentContent.substring(length+offset,
         currentLength);
       String newValue = before + after;
       currentValue = checkInput(newValue, offset);
       super.remove(offset, length);
     }
     public int checkInput(String proposedValue, int offset)
         throws BadLocationException {
       if (proposedValue.length() > 0) {
         try {
           int newValue = Integer.parseInt(proposedValue);
           return newValue;
         } catch (NumberFormatException e) {
           throw new BadLocationException(proposedValue, offset);
         }
       } else {
         return 0;
       }
     }
   }

E depois, sete seu TextField

Document textDocOne = new IntegerDocument();
        jTextField1.setDocument(textDocOne);

E já era

B

“Superxis”:
Muito bom Bruno! Deu certo

Se souber me dizer… quem dispara os métodos dessa classe? Como sei os nomes que elas devem ter?

Como assim que nomes elas devem ter?
Agora, quem dispara os metodos não sei mesmo te dizer…

S

Me referi aos nomes que elas devem ter supondo que sigam um padrão e que assim possam ser reconhecidas e disparadas automaticamente por sejá lá o que for 8O

Abraços :lol:

Criado 11 de julho de 2007
Ultima resposta 13 de jul. de 2007
Respostas 6
Participantes 3