2

I have a semi-theoretical problem involving Java and Swing. Swing components contain two options to respond to the user: setAction and addActionListener. These pertain to the Action and ActionListener objects, respectively.

My question is: which method, setAction or addActionListener, should I use? And how are they different from each other?

sdasdadas
  • 23,917
  • 20
  • 63
  • 148

2 Answers2

3

Personal preference is to use Action where possible (it doesn't always make sense to do so). The main reasons are:

  • Simplifies the code. You don't end up with a actionPerformed method that is 100's of lines long with multiple if-else statements. The Action contains a specific operation to a specific class.
  • They are self contained (this is related to the previous point). All the information need to configure the UI elements is self-contained to the Action, making it easier and quicker to setup, not to mention consistent ;)
  • They are reusable, menus, buttons, key bindings, text fields.
  • They are extendable. You can create a basic concept of an action for a group and extended the base to provide the implementation requirements for individual actions (I do this a lot with key bindings)

IMHO

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
2

According to http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html

An Action object is an action listener that provides not only action-event handling, but also centralized handling of the state of action-event-firing components such as tool bar buttons, menu items, common buttons, and text fields. The state that an action can handle includes text, icon, mnemonic, enabled, and selected status.

Looking at the linked documentation and this answer, it seems one reason to use Actions could be trying to use the same Action on several objects

Community
  • 1
  • 1
Daniel
  • 2,435
  • 5
  • 26
  • 40
  • Thanks for the answer - I accepted the other because this is fairly similar to the answer of the duplicate posted above. Also, the other one provides a bit of real world motivation. – sdasdadas Jun 19 '13 at 21:40