Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Add DocumentListener to validate multiple JTextFields  RSS feed

 
rayan alex
Ranch Hand
Posts: 33
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Code given below does real time validation for 2 JTextFields. While entering some values to txt1 and txt2 enables the save button and removing values from txt2 or txt1 reset the save button to disable. I use Netbeans as IDE.
What I want to do is, enable Save button after checking multiple JTextFields for validity. If any of the text fields is empty, btnSave must be disabled.
This program gives expected result up to some extent. But there is little issue. After form appears for the first time, When I type something on Textfield1, Save button enables without checking Textfield2. This happens only at the first time.

 
Paul Clapham
Sheriff
Posts: 22185
38
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you have looks reasonable enough to me, except that the use of SwingUtilities.invokeLater looks wrong. It certainly isn't necessary and it may be part of your problem.

Your code is rather verbose, as well. (The more code you have, the more likely you are to have bugs.) For example I would rewrite the body of the validFormatterLimit() method like this:

 
Paul Clapham
Sheriff
Posts: 22185
38
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually now that I look at your code more closely, the problem is with lines 3 and 4 of what you posted. Initially the text fields are empty, right? So why did you choose those values to initialize those variables?
 
Rob Camick
Ranch Hand
Posts: 2753
11
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. Don't use Boolean variables. Use boolean primitive for cases like this.
2. Don't create code that is dependent on a fixed number of components. What happens if you ever need to handle 3 text fields. You code will become a lot more complex.

Instead create a general solution that will work for any number of text fields. Something like:

 
Charles Sexton
Ranch Hand
Posts: 273
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Camick wrote:2. Don't create code that is dependent on a fixed number of components. What happens if you ever need to handle 3 text fields. You code will become a lot more complex.



code refactoring is part of learning java and this advice can't given out enough.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!