Bom dia, pessoal.
Preciso que um JTextField permita somente 4 números, como posso fazer isso?
Tentei bastante antes de criar o tópico. Fiz o seguinte:
Criei uma classe NumCheck para ver se o caracter é um número:
[code]public class NumCheck extends PlainDocument
{
private boolean numero;
public NumCheck(boolean isNumber)
{
super();
numero = isNumber;
}
public void insertString(int offs, String str, javax.swing.text.AttributeSet a)
throws BadLocationException
{
if(numero == true)
{
for (char c : str.toCharArray())
{
if(!Character.isDigit(c))
{
return;
}
}
}
super.insertString(offs, str.toUpperCase(), a);
}
}[/code]
private JTextField txtid = new JTextField();
txtid.setDocument(new NumCheck(true));
E uma classe MaxLengthText para limitar o número de chars:
[code]public class MaxLengthText extends PlainDocument{
private int maxchars;
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException{
if(str != null && (getLength() + str.length() < maxchars)){
super.insertString(offs, str, a);
}
}
public int getMaxchars() {
return maxchars;
}
public void setMaxchars(int maxchars) {
this.maxchars = maxchars;
}
}[/code]
private MaxLengthText m5 = new MaxLengthText();
m5.setMaxchars(5);
txtid.setDocument(m5);
Acontece que os dois não funcionam juntos. Deixando do jeito que está, eu consigo limitar o campo para somente permitir números, mas o número de caracteres não é alterado.
Como posso resolver isso?
Obrigado.
