• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to implement actionlistener  RSS feed

 
Torvald Helmer
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • 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 ]
 
Tony Docherty
Bartender
Posts: 3268
82
  • Mark post as helpful
  • send pies
  • 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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!