• Post Reply Bookmark Topic Watch Topic
  • New Topic

ActionListener question  RSS feed

 
Agapios Hartzoulakis
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I'm trying to figure out the best approach for the use of ActionListener. Is it better to have it in the GUI class as an inner class or in a separate file?
For example if we have a GUI with many menuitems, implementing the ActionListener as an inner class will lead us to a very big and complicated file (although it is easier to control the gui objects (menus, textfields etc) this way). Is it possible to impmement it as a class in a separate file and how must i declare the variables?( public, private, static etc)
Thanks in advance
 
Campbell Ritchie
Marshal
Posts: 56223
171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you sure you oughtn't to be on the AWT/Swing forum?

My opinion is, where you put a Listener depends on where you are using it, and what for:-
  • 1: A Listener used once and once only and substantially different from all other Listeners: use an anonymous inner class.

  • No two ways about it.
  • 2: A Listener used in more than one place, either with the same action, or with similar actions: use a Listener class.
  • 3: A Listener which applies specifically to the Component it is set on, eg the sort of thing where you show number which represent the mouse position: use addActionListener(this).

  • If you have all your menu in the same overall class, I don't think it matters too much whether you use inner classes or not. If you use an inner class, make its class declaration and fields private, and the methods public. That will allow access (despite the public keyword) from inside the surrounding class.

    If you have similar Listeners in different classes in your GUI, you can probably best use a separate class for each Listener. Put the Listener classes in the same package as your GUI, and leave out the access modifiers altogether; that is "default" access, which means access only from within the same package. Make sure to comment every place you use default access, because its use is unusual.
     
    Ken Blair
    Ranch Hand
    Posts: 1078
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    In just about every case I can think of I use an inner class. Whether it's anonymous or a member depends on the situation.
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!