• Post Reply Bookmark Topic Watch Topic
  • New Topic

KeyListners Vs Own Functions? What should i prefer for validation of JTextfields?  RSS feed

 
Bharvi Dixit
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all
In my Jframe validations are needed for JTextfields. I am little confuse that should i go for KeyListners or Should i use methods for validating the inputs. Which one is more efficient??
By writing own methods means for example.. if i want to a texfield to take only digits as input i havve written this method:



Please reply.


Thanks in advance
 
Campbell Ritchie
Sheriff
Posts: 53779
128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That has some poor features in; returning true from false, and even worse using == false. It is a poorly‑named method and does not appear to me even to return true from digits. And Double.toString(d) will not necessarily give the same String value as was entered in the text field.

What is wrong with a regex? You can apply it to the text itself. You can probably find a regex for doubles if you Google “regular expression for Java floating-point numbers”.
 
Rob Camick
Ranch Hand
Posts: 2756
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if i want to a texfield to take only digits


Then you should use a Document Filter or use a JFormattedTextField.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!