Estou tentando montar uma validação de campo que só aceita números, nisso, estou usando o evento KeyPressed onde quero verificar se o evt.getKeyChar() está contido em 0…9.
Se não estiver, não aparecerá no campo de texto.
Gostaria de saber, como montar if simplificado, sem OR, verificando e o KeyChar está contido em 0…9.
importjava.text.*;importjava.awt.event.*;importjavax.swing.text.*;importjavax.swing.JTable;/** * Controls the text being entered into a text field. Only numbers are accepted. * Intended to be used with "textField.addKeyListener(new KeyAdapter())"; * *@author wferreira */publicfinalclassToolNumericKeyAdapterextendsKeyAdapter{privateint_maxLength=Integer.MAX_VALUE;privateboolean_allowPoint=false;publicstaticfinalintINTEGER=1;publicstaticfinalintFLOATING_POINT=2;privateDouble_upperLimit;privateDouble_lowerLimit;privateNumberFormatdoubleFormat=NumberFormat.getInstance();publicToolNumericKeyAdapter(intmaxLength){_maxLength=maxLength;_allowPoint=true;}publicToolNumericKeyAdapter(intmaxLength,booleanallowPoint){_maxLength=maxLength;_allowPoint=allowPoint;}publicvoidsetUpperValueLimit(doublelimit){_upperLimit=newDouble(limit);}publicvoidsetLowerValueLimit(doublelimit){_lowerLimit=newDouble(limit);}publicvoidkeyTyped(KeyEvente){chartypedChar=e.getKeyChar();if(!Character.isISOControl(typedChar)){JTextComponentsource=(JTextComponent)e.getSource();Stringtext=source.getText().trim();if(typedChar!=','&&typedChar!='.'&&!Character.isDigit(typedChar)||(text.length()>=_maxLength)){java.awt.Toolkit.getDefaultToolkit().beep();e.consume();return;}StringBufferbuffer=newStringBuffer(text);if(typedChar==','){try{source.getDocument().insertString(source.getCaretPosition(),".",null);}catch(BadLocationExceptionex1){}e.consume();}else{buffer.append(typedChar);}text=buffer.toString();if(text.length()!=0){doubleval=0.0;try{val=doubleFormat.parse(text).doubleValue();}catch(ParseExceptionex){thrownewIllegalArgumentException("Should never allow invalid numbers to enter: "+text);}if((_upperLimit!=null&&_upperLimit.doubleValue()<val)||(_lowerLimit!=null&&_lowerLimit.doubleValue()>val)){java.awt.Toolkit.getDefaultToolkit().beep();e.consume();return;}}}}}
Ou então voce pode adicionar um DocumentListener ao Document do JTextField e validar lá.
J
jessicabnu
Apliquei a classe. Muito obrigada!
lina
Oi,
Ou melhor que isso… Crie uma classe que extends o componente de texto e implemente uma inner-class que extends o PlainDocument (para manipulação do documento), só sobreescreva o método insertString para o desejado.
Tchauzin!
J
joellazzari
Abri um tópico a dois dias atrás, trata inclusive disso que a jessicabnu precisa: JTextField que aceite somente números.
Quero fazer algo parecido com o que a lina mencionou: extender PlainDocument para controlar JTextField (para valores monetários, datas, somente números, somente letras, etc).
O ViniGodoy tem me ajudado muito no tópico, com algumas dicas preciosas, mas não consegui evoluir muito na solução.
lina e Mark_Ameba (tem uma classe lá que peguei de uma resposta sua), querem dar uma olhada?