-3

I use this code to restrict the input only for numbers, but if the first key I press is a letter, the code let me enter that letter, only one time, then when I erase it I cannot input anymore letters, what is wrong with the code? I want to imput only numbers.

amount.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) {
        char c = e.getKeyChar();
        if (!(Character.isDigit(c)))
                e.consume();
        }

}); 

I added the two closing parentheses, still the same results, here is a video

Lazaro
  • 37
  • 5
  • 1
    Or a JFormattedTextField or a JSPinner. The [Swing tutorial](http://docs.oracle.com/javase/tutorial/uiswing/components/componentlist.html) has more information on these components. – camickr Nov 26 '15 at 16:11
  • hi, thanks for your coments, I know there are other options to do this, but I want to understand why this happens. – Lazaro Nov 26 '15 at 16:14
  • Works flawlessly here. Except that I had to add two closing parentheses. Other than that, working great. Can you make sure this is the faulty code? – mr.celo Nov 26 '15 at 16:32
  • I added the two parentheses, but it doesnt work for me, I post a small video showing the problem – Lazaro Nov 26 '15 at 19:30
  • Stop using `KeyListener`'s on text components! This is not appropriate! Use `DocumentFilter` if your MUST do it yourself or `JSpinner` or `JFormattedTextField` which have been designed to do this job – MadProgrammer Nov 26 '15 at 22:31
  • *"but I want to understand why this happens."* - Because there are more things going on within the API then you are taking into account. There is no guarantee in which order your `KeyListener` will be notified and the key may have already been processed by the fields `KeyListener` and the `Document` updated. It's also possible that other `KeyListener`s are ignoring the `isConsumed` property (you are). Text handling is a complex subject and the API has well defined mechanisms for handling the functionality you are trying to implement, you should use those to avoid this kind of weridness – MadProgrammer Nov 26 '15 at 22:34
  • Thanks for the explanation MadProgramer, recomendation: you should get out more :) – Lazaro Nov 26 '15 at 23:49

1 Answers1

0

Try this:

try{
        Double.parseDouble(c);

        //Code here for TRUE case (Is Number)

}catch(NumberFormatException e1){

        //Code here for FALSE case (Is NOT Number)
}
Mayuso
  • 1,291
  • 4
  • 19
  • 41