Can anyone tell me how to use Java Keylistener to add validations in my java gui form??
eg. I have a textfield. I want to enter only alphabets in it. I dont want any numerics. So when a user tries to type a numeric value in it, I want to prompt a message. But how can I have do it in java?
Can use of keylistener be helpful??

Recommended Answers

All 3 Replies

  1. don't use KeyListener for JTextComponents, use DocumentListener,

  2. use JFormattedTextField,

  3. I'd be to use DocumentFilter with Pattern, filtering for non_alphabets chars, then there no needed any prompt about non_number char is inputed,

Ofcourse , you have to use KeyListener.

Go through KeyListener and KeyEvent classes . The KeyEvent class will be useful for comparing what keys have been pressed.

Google some keylistener examples and based upon that build your own logic.

For example , if you dont want to allow numerics, then you can place a simple IF statement

if(pressed key = KeyEvent.VK_0 || pressed key = KeyEvent.VK_1 .........upto 9)
{
  JOption.ShowMessageDialog(this,"you have pressed a numeric key ...");
 }

No, you don't have to use KeyListener.
mKorbel's advice is good. Apart from anything else his approach will also handle copy/paste into the field correctly. It also uses classes that Sun/Oracle have already written for this purpose, so no need to re-invent the wheel.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.