Uma solução sugerida pelo pessoal no fórum da Sun:
CODE
import javax.swing.*;
import javax.swing.text.*;
class MyTextVerifier extends PlainDocument
{
public void insertString(int offset, String str, AttributeSet attSet)
throws BadLocationException
{
boolean valid = false;
if (str == null) return;
String old = getText(0, getLength());
String newStr = old.substring( 0, offset ) + str + old.substring( offset );
valid = isValid(newStr);
if (valid) super.insertString( offset, str, attSet );
}
public boolean isValid(String str) {
return str.length() < 10;
}
}
class Teste extends JFrame {
public Teste()
{
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField f = new JTextField();
f.setDocument(new MyTextVerifier());
add(f);
}
public static void main(String[] args) {
Teste t = new Teste();
t.setVisible(true);
}
}
Na função isValid() você pode acrescentar outras opções de validação.