Eu implementei a classe LengthLimitedField que faz exatamente isso. Eu
usei como base um exemplo do Java Tutorial.
De uma olhada no programa em anexo.
Carlos Daniel Chacur Alves wrote:
>
> Caros colegas,
>
> Estou implementando uma varia��o de JTextFields que aceitam no
> m�ximo n caracteres digitados. Contudo, estou tendo problemas
> com rela��o � utiliza��o do m�todo consume() no m�todo keyPressed (a
> classe que estou escrevendo estende JTextField e implementa
> a interface KeyListener). O fato � que os caracteres que excedem o
> limite continuam a aparecer (o mesmo n�o acontece quando utilizo
> TextField
> em vez de JTextField). O trecho do c�digo a que me refiro � o seguinte:
>
> if ((key == KeyEvent.VK_TAB) || (key == KeyEvent.VK_ENTER)) {
> ((Component) (e.getSource())).transferFocus();
> }
> else if ((key != KeyEvent.VK_LEFT) && (key !=
> KeyEvent.VK_BACK_SPACE) && (super.getText().length() > maxLength)) {
> e.consume(); // N�o est� tendo o comportamento desejado!!!!
> .
> .
> .
> }
>
> Algu�m tem uma sugest�o para a solu��o desse problema?
>
> Obrigado desde j�,
>
> Carlos Daniel
>
> --------------------------- LISTA SOUJAVA ---------------------------
> http://www.soujava.org.br - Sociedade de Usu�rios Java da Sucesu-SP
> [para sair da lista: http://www.soujava.org.br/forum/cadastrados.htm]
> ---------------------------------------------------------------------
--
Eduardo Issao Ito <[EMAIL PROTECTED]>
Eurosoft Consultoria <http://www.euroconsult.com.br>
Rua Marina Saddi Haidar, 176 - S�o Paulo - SP - Brasil
CEP 04650-050
TEL: +55 11 524-8022
FAX: +55 11 524-0408
import javax.swing.*;
import javax.swing.text.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
public class LengthLimitedField extends JTextField {
private int thisLen = 0;
private int maxLen = Integer.MAX_VALUE;
public LengthLimitedField () {
super();
}
public LengthLimitedField(int cols, int maxLen) {
super(cols);
this.maxLen = maxLen;
}
public LengthLimitedField(int maxLen) {
super(0);
this.maxLen = maxLen;
}
protected Document createDefaultModel() {
return new LengthLimitedDocument();
}
class LengthLimitedDocument extends PlainDocument {
public void insertString(int offs, String str, AttributeSet a) throws
BadLocationException {
if (str == null || thisLen >= maxLen)
return;
if (thisLen + str.length() > maxLen)
str = str.substring(0,maxLen - thisLen);
thisLen += str.length();
super.insertString(offs, str, a);
}
public void remove(int offs, int len) throws BadLocationException {
thisLen -= len;
super.remove(offs, len);
}
}
}