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

attaching same listener to multiple components  RSS feed

 
Jessica Dancel
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any reason not to attach one listener to multiple GUI components?

For example, I'm working on a form with a Modify button in it. I have an action listener that will trigger when a component is changed. Can I attach this listener to every component in the GUI? Or do I need to use separate ones for each one? All the example code I have uses separate ones, and I'm not sure if this is a style issue or a language construct.

Thanks in advance!
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a handler is going to do the same thing no matter who invokes it (except for using data it gets from the caller -- i.e., the contents of the JTextField it was invoked by) then using one listener for many components is not only OK, it's good practice.

But if you need to do different things for different invokers, then combining listeners just makes for messy and inefficient code. Better to put each separate action into its own listener, and use separate objects instead of explicit decision-making at runtime to decide what to do.
 
Jessica Dancel
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for your answer. That answers my question!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!