next up previous
Next: Nested Class Definitions and Up: The Frightened Freshers Guide Previous: Adding a Menu Bar

The ActionListener Interface

So what is this magical thing of doom? Well if you are not sure quite what an interface is, its basically something that says to the class that implements it YOU MUST IMPLEMENT THE METHODS I CONTAIN. And thats about it. If you knew this already then thats okay, if not it may be worth flicking over the lecture slides for the lectures about inheritance.

Anyway, onto the ActionListener Interface. It has a single method, actionPerformed. When something happens to an AWT or Swing object, the Class that the GUI was built in is told `hey, something happened!'. In practice, this means your Class needs to do something when the Quit button is pressed to stop a dumb user from wondering why your application does not quit when there is in fact no quit code...

Once again, the following code is ripped from the slides.


\begin{lstlisting}
public class ImageViewer implements ActionListener
{
// wind...
...menu creation code here
openItem.addActionListener(this);
}
}
\end{lstlisting}

So, what on earth is this chunk of code doing? The bit you should be concerning yourself with is the actionPerformed section. What this is doing is that it is triggered whenever the Menu items are clicked on and generates an ActionEvent. This method grabs the name of the command and then does some simple String comparison to figure out exactly what generated the ActionEvent and do stuff as it sees fit. Possibly the most important part of this code comes afterwords with the openItem.addActionListener code, this says to the openItem `Whenever you have an ActionEvent, please tell me!'. Note that you will need to add action listeners to all the Menu items and any other clickable objects you may create.

Events generated will correspond to User Interface interactions, such as clicking a button or on a menu item. Frames will generate WindowEvents and Menus will generate ActionEvents. Objects that are notified when an ActionEvent or WindowEvent is generated are called Listeners.

The (really) major issue with this style of catching whatever events are generated is that you need additional things in the if statement whenever you add more buttons. Also, if you change the captions on your menu items then the actioncommand they generated and you will need to once again edit the if statement. Basically this method of catching events really sucks unless you are using it for a very, very small application with almost no buttons or menus.

So how about we have a somewhat better example?


next up previous
Next: Nested Class Definitions and Up: The Frightened Freshers Guide Previous: Adding a Menu Bar
Tom Carlson 2006-02-16