• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

How to implement actionlistener

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have three classes, main-method, frame, and a menu-class.



which contains all elements regarding the menu added
to the frame class.

The frame class:



If I want to have the actions in the frame-class, how do I proceed when all the menuitem are located in another class, or is it even easier to have a separate class containing all action?
[ August 21, 2007: Message edited by: Torvald Helmer ]
 
Bartender
Posts: 3323
86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First of all you shouldn't be calling your own classes Frame, Menu etc as these are already defined classes in the jdk. It's not that you can't use the same names (they will be in different packages so they are distinguishable from each other) it's just very confusing especially if you plan to ask for help from other people on forums such as this. Give them some meaningful names eg if you are modelling a Garage call them GarageFrame and GarageMenu.

To answer your question: the class that handles the menu action can be anywhere you want it to be (as long as the class containing the code implements ActionListener). But, and there's always a big 'but' or two to these sort of things:

1. It's generally not a good idea for one class to handle all the actions or you end up with one actionPerformed method which is full of code just to work out which menu was pressed (which sort of defeats the point of using actionlisteners).
2. Whilst you can put the code anywhere you want there are clearly good and bad places to put it in terms of how appropraite it is to the class containing it.

The standard approach to this is to create a anonymous inner classes to handle each menu's action event and use them to call the appropriate methods in other classes.
reply
    Bookmark Topic Watch Topic
  • New Topic