21.3. Supporting the File Menu

To support the menu items in the File menu, you must add some code to the actionPerformed() method in the FileAction class. You can try to put a skeleton together but a problem presents itself immediately: The ultimate source of an event will be either a toolbar button (a JButton object) or a menu item (a JMenuItem object) that was created from a FileAction object. How do you figure out what action originated the event? You only have one definition of the actionPerformed() method shared amongst all FileAction class objects so you need a way to determine which particular FileAction object originated the event. That way you can decide what you should do in response to the event.

Each FileAction object stores a String object that was passed to the constructor as the name argument, and this string was then passed on to the base class constructor. If only you had thought of saving it, you could compare the name for the current object with the name for each of the FileAction objects in the SketchFrame class. Then you could determine for which object the actionPerformed() method was called.

All is not lost though. You can call the getValue() method for the ActionEvent object to retrieve the name for the action object that caused the event. You'll be able to compare that with the name for each of the FileAction objects that you store as members of the SketchFrame class. You can therefore implement the actionPerformed() member of the FileAction inner class ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.