8

Myself, I always use ActionListener as swing event-handler (e.g. button-click), and it is the most common listener I've seen in most swing applications.

However, Some Swing professionals here in stackoverflow often advise to use Action rather than ActionListener. What benefits I get from doing so?

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417

1 Answers1

10

An Action is preferred if you need to share functionality across components. From the docs

if you have two or more components that perform the same function, consider using an Action object to implement the function.

but also says

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.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • 1
    +1 for `Action`; [`FileMenu`](http://stackoverflow.com/a/4039359/230513) is a basic example. The benefit of doing it is not having to do it latter. :-) – trashgod Feb 24 '13 at 13:40
  • 2
    What about creating a single action listener, and add the same reference to multiple swing components via `addActionListener()`? Isn't it the same thing? – Eng.Fouad Feb 24 '13 at 13:40
  • 5
    @Eng.Fouad: Actions have other additional goodies not found with ActionListeners including the ability to hold Icons, mnemonic keys, descriptions, and to hold any value-key you'd like. – Hovercraft Full Of Eels Feb 24 '13 at 13:43
  • 1
    @HovercraftFullOfEels Ah I see +1. I like the last part more :) `and to hold any value-key you'd like`. +1 for Reimeus. – Eng.Fouad Feb 24 '13 at 13:49
  • 2
    @Eng.Fouad: It's also a good way to export functionality from a library, for [example](http://stackoverflow.com/a/14202720/230513). – trashgod Feb 24 '13 at 13:51