Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

actionPerformed Best Practices  RSS feed

 
Chris Waguespack
Ranch Hand
Posts: 36
Eclipse IDE Flex Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was wondering what some best practices might be for using actionPerformed and other events.

The first way is

which I don't think would be as good, as you are having to create and load a class for each listener you have.

The second way is to have your GUI class implement ActionListener and create an actionPerformed method that checks if the event's source is equal to the variable name for the action you want to do.

Any thoughts?

Thanks,
Chris
 
Gregg Bolinger
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In general I tend to use the AIC approach unless the action needs to be shared across components (toolbars, menus, etc). For those cases I create Action classes that extend AbstractAction.

I can't remember the last time I implemented ActionListener and checked for the component. This always seemed like silly unneeded work to me.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Chris Waguespack:

The first way is

which I don't think would be as good, as you are having to create and load a class for each listener you have.


Which wouldn't be good because...?
 
Chris Waguespack
Ranch Hand
Posts: 36
Eclipse IDE Flex Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just thought that the creation of classes might take extra time/memory. If that's not true, then I guess there's no reason not to use aics.

-Chris
 
Rob Spoor
Sheriff
Posts: 21088
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The classes are created at compile time. At runtime, it's just another object.

Sure, having your main object implement ActionListener will save you those few objects, but is that worth the bad design? Because that's exactly what that is:
- the actionPerformed method is public, and other classes could potentially use it as an action listener (although that wouldn't have any effect since the source would be wrong)
- instead of keeping the logic for all buttons / controls separate, you integrate them in one huge method, separating them again - using if statements.
 
Chris Waguespack
Ranch Hand
Posts: 36
Eclipse IDE Flex Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, thanks for the clarification.

- Chris
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!