2

By convention, where should the ActionListener for a user inteface go? I have several options but none of them seem quite right.

Shorthand:

  • GUI - main class that contains all the JPanels/displayable objects
  • Logic - main class that handles application logic

  1. I could in-line declare a new ActionListener in GUI, store it, and then it/pass its pointer around to where it's needed.
  2. I could make GUI itself implement ActionListener and pass a reference to itself to where it's needed.
  3. I could in-line declare a new ActionListener in the main logic (this makes sense since the actions the buttons do are logic that shouldn't be in the GUI) and then pass it to GUI which will pass it to where it's needed.
  4. I could write the logic in a whole new file GUIListener.java and declare GUIListener where it's needed/pass it around.
  5. Some other method, I'm sure there are tons.
wonton
  • 7,568
  • 9
  • 56
  • 93
  • 5
    Don't do (3), keep UI and interaction stuff out of business logic. Suppose you want to have a webapp later that operates on the same data as your current swing app - if your logic code is cluttered with ActionListeners, you can't just reuse it. – us2012 Jan 06 '13 at 05:09
  • 5
    A lot will come down to what you want to achieve, but you might like to have a look at [How to use Actions](http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html). – MadProgrammer Jan 06 '13 at 05:11
  • 2
    Have a look at `javax.swing.text.DefaultEditorKit` & `javax.swing.text.StyledEditorKit` for an example of reusable `Action` classes. – trashgod Jan 06 '13 at 09:21

1 Answers1

2

This basically poses a question of Separation of Concerns. In my opinion you should keep GUI, Controller and Model(bean) objects in separate files. Controller facilitating all the processing related to application.

pratikch
  • 670
  • 5
  • 19