Controlar tamanho do campo JTextField

Olhem amigos estou tetando fazer um objeto para controlar o tamanho do campo mas o que acontece e que JTextField ta sobreescrvendo o outrto olhem o meu fonte.

/**Função para verifcaar o tamanho da String*/
    public void getTamanho(int t, javax.swing.JTextField tx){
        txt = tx;
        tam = t;
        txt.addKeyListener(
        new java.awt.event.KeyAdapter(){
            public void keyTyped(java.awt.event.KeyEvent e){
                if(tam <= txt.getText().length()){
                    txt.setText(txt.getText().substring(0,tam - 1));
                }
            }
        }
        );
    }
    private int tam;
    private javax.swing.JTextField txt;

Alguem sabe omo arrumar isso para um Jtextfield não sobrescrver as funções do outro, ou se alguem ja fez de foma diferente e querer mostrar agradeço

Jefferson Martins

Jefferson,

Eu fiz assim e funcionou :

Componente.addKeyListener(new KeyAdapter()
		{
			public void keyTyped(KeyEvent k)
			{
				char c = k.getKeyChar();
				int key = (int) c;
				if(Componente.getText().trim().length() == 30)
					if(Character.isLetter(c) || Character.isDigit(c) || Character.isSpaceChar(c) || Character.isDefined(c))
						if(key != KeyEvent.VK_BACK_SPACE)
							k.consume();
			}
		});

[]´s

Ola,

Se vc estiver usando java 1.4.x, de uma olhada em:

javax.swing.text.DocumentFilter
javax.swing.text.AbstractDocument

Vc deve usar essas classes para não deixar o usuário inserir mais caracteres do q o necessário.

Caro vc não use o jdk1.4.x, vc pode dar uma olhada no tutorial aqui mesmo no guj:

http://www.guj.com.br/servlet/guj?PARSE=true&MAMUTE_ACTION=br.com.guj.action.ListTutorial&MAMUTE_TEMPLATE=ShowTutorial&LIST_TUTORIAL=single&TutorialId=29&PAGE=1

[]'s

Ola galera blz …

Amigo eu fiz uma classe que faz isso que vc quer alem de outras coisas mais como (Somente numero,Somente Textos em Maiuscula/Minusculas) olha ae.

/*
 * DocumentPro.java
 *
 * Created on 29 de Janeiro de 2003, 09:10
 */

package util;

/**
 *
 * @author  William J. Oliveira
 */

import javax.swing.*;
//import java.lang.Character.*;
import javax.swing.text.*;

public class DocumentPro extends PlainDocument {
    
    public static final int NORMAL      = 0;
    public static final int NUMERICO    = 1;
    public static final int CHARMAP     = 2;
    public static final int MAIUSCULA   = 3;
    public static final int MINUSCULA   = 4;
    
    private int iMaxLength;
    private int iTipo;
    private char[] charMap;
    
    public DocumentPro() {
        super();
        this.iMaxLength = 0;
        this.iTipo = 0;
    }
    
    public DocumentPro(int maxlen) {
        super();
        this.iMaxLength = maxlen;
        this.iTipo = 0;
    }
    
    public DocumentPro(int maxlen, int tipo) {
        super();
        this.iMaxLength = maxlen;
        this.iTipo = tipo;
    }

    public DocumentPro(int maxlen, int tipo, char[] ch) {
        super();
        this.iMaxLength = maxlen;
        this.iTipo = tipo;
        this.charMap=ch;
    }
    
    public void setMaxlen(int maxlen){
        iMaxLength = maxlen;
    }
    
    public int gettMaxlen(){
        return this.iMaxLength;
    }
    
    public void setTipo(int tipo) {
        this.iTipo = tipo;
    }
    
    public int getTipo() {
        return this.iTipo;
    }
    
    public void setCharMap(char[] ch) {
        this.charMap=ch;
    }
    
    public char[] getCharMap() {
        return this.charMap;
    }
    
    public void insertString(int offset, String str, AttributeSet attr)
    throws BadLocationException    {
        
        if (str == null) return;                    
    
        
        switch(this.iTipo) {
            case 0:                
                break;
            case 1:                
               {
                Character ch=new Character(str.charAt(0));                        
                if (!ch.isDigit((str.charAt(0)))) return;
                break;
               } 
            case 2:
                if(!existCharMap(str)) return;
                break;
            case 3:                
                str=str.toUpperCase();
                break;
            case 4:
                str=str.toLowerCase();
                break;
        }
        
        if (iMaxLength <= 0) // aceitara qualquer no. de caracteres
        {
            super.insertString(offset, str, attr);
            return;
        }
        
        int ilen = (getLength() + str.length());
        if (ilen <= iMaxLength){ // se o comprimento final for menor...
            super.insertString(offset, str, attr); // ...aceita str
        } else {
            if (getLength() == iMaxLength) return; // nada a fazer
            String newStr = str.substring(0, (iMaxLength - getLength()));
            
        }
        
    }
    
    protected boolean existCharMap(String str) {
        for(int i=0;i<this.charMap.length;i++) {           
           if(str.indexOf(charMap[i])>=0) return true;
        }
        
        return false;
    }    
 
}