This week's book giveaway is in the Java 9 forum.
We're giving away four copies of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications and have Sander Mak & Paul Bakker on-line!
See this thread for details.
Win a copy of Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications this week in the Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Enable JButton when 3 fields are filled in  RSS feed

 
Dennis Putnam
Ranch Hand
Posts: 377
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a JButton that I want to enable only when 3 specific fields (there are a many other fields) of a JDialog are filled in. What is the best way to do this? I'm thinking I need to check the value of each of those fields each time any one of them is updated but that seems kind of burdensome. Is there some other better way? TIA.
 
Campbell Ritchie
Marshal
Posts: 56193
171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you add document listeners to the three fields? Trigger the action when any of them is changed, and myButton.setEnabled(!box1.getText().isempty() && ...)
Set a Timer which checks the three fields every second, 0.1second, or similar?
 
Rob Camick
Ranch Foreman
Posts: 2818
15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm thinking I need to check the value of each of those fields each time any one of them is updated but that seems kind of burdensome


That is the easiest way to do it.

The trick is to create a simple API so that your solution scales whether you have 2 text fields or 20 text fields to check. In other words you don't do the check based on variable names.

You can create a class to register text field you want to check and store the text fields in a List. You add a DocumentListener to each text field. Then you simply iterate through the List whenever a DocumentEvent is generated.

 
Dennis Putnam
Ranch Hand
Posts: 377
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can create a class to register text field you want to check and store the text fields in a List. You add a DocumentListener to each text field.

I hadn't thought of that. I'll give it a try. Thanks.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!