I have tried to use the example shown here but java showing error message of
"AttributeSet cannot be resolved to a type"
That is why I am trying to use another method of allowing only digits:
txtUsername.addKeyListener(new MyKeyListener());
public class MyKeyListener extends KeyAdapter{
public void keyPressed(KeyEvent ke){
System.out.println("Key pressed code = "+ke.getKeyCode());
if (ke.getKeyCode()>=48 && ke.getKeyCode()<=57)
return true;
else
return false;
}
}
But of course it is not working because keyPressed
method is void
. So, what to do in order to print only digits in textfield?
Here check this code snippet, that's how you allow only digits in JTextField, by using DocumentFilter, as the most effeciive way :
Or one can simply use this approach, as given by @Carlos Heuberger
This is what I use to consume non-numbers
Try this:
instead of:
I'd suggest using a JFormattedTextField, Here is how : How to Use Formatted Text Fields