File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Deleting a numeric in JTextField Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Deleting a numeric in JTextField" Watch "Deleting a numeric in JTextField" New topic

Deleting a numeric in JTextField

Ravindra Rana

Joined: Sep 10, 2008
Posts: 10
What i am trying in below lines to Delete the numeric char from myJTextField if its at first position.
But the thing i get is not what i expect.
If i enter 5 and then 7, it deletes the 5 but 7 remains in field.

Note : If i have used the e.consume() then i am not able to use numerics other then 1st position.

All inputs are welcomed.

Darryl Burke

Joined: May 03, 2008
Posts: 5115

Use a DocumentFilter, not a KeyListener.

With your present code, what would be the result of pasting a digit by Ctrl-V?

luck, db
There are no new questions, but there may be new answers.
Ravindra Rana

Joined: Sep 10, 2008
Posts: 10
Thanks for the help. Previously tried DocumentListener but didn't get much help.
With KeyListener, Ctrl-V append each digit to its predecessor.
But with my new code it is NULL. Thanks.
But the other side is that seems that it allows only one character and then throws exception (a NullPointerException without any specific function so not of much help to debug)

What i am trying to check is that first char must be an ALPHA (either Uppercase or Lowercase) but must not be a Numeric.

If i have used
then it was not allowing any character. Seems like it checks the ASCII values of entered char.
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

So you want the field to always start with a letter, if it contains anything at all? Seems to me you should be looking at some after-the-fact validation, rather than trying to interfere with what the user is typing in. Maybe a JFormattedTextField?

And by the way, checking that something is not a digit is an inadequate way to check that it is a letter.
Ravindra Rana

Joined: Sep 10, 2008
Posts: 10

Thanks for the valuable help.
I just added an ELSE block and the code works fine. btw now i am using a customized myFilter class in which i placed the below method.
My myFilter class extends PlainDocument which in turn extends AbstractDocument. So i am able to override replace method
My myFilter class restricts the input to Albhabets+Numeric+SomeSpecialCharacters but it starts with only an alphabet.

PS: Now the code also handle Ctrl-V for numerics at first position. Claps for Darryl.
I agree. Here's the link:
subject: Deleting a numeric in JTextField
jQuery in Action, 3rd edition