Java Reference
In-Depth Information
Exercise 11.9 Add three private methods to your class, named openFile , saveFile ,
and quit . Change the actionPerformed method so that it calls the corresponding method
when a menu item is activated.
Exercise 11.10 If you have done Exercise 11.6 (adding a Help menu), make sure that its
menu item also gets handled appropriately.
We note that this approach works.
We can now implement methods to handle menu items to do our various program tasks. There
is, however, one other aspect we should investigate: the current solution is not very nice in
terms of maintainability and extendibility.
Examine the code that you had to write in the actionPerformed method for Exercise 11.9.
There are several problems. They are:
You probably used an if statement and the getActionCommand method to find out which
item was activated. For example, you could write:
if(event.getActionCommand().equals("Open")) ...
Depending on the item label string for performing the function is not a good idea. What if
you now translated the interface into another language? Just changing the text on the menu
item would have the effect that the program does not work anymore. (Or you would have
to find all places in the code where this string was used and change them all—a tedious and
error-prone procedure.)
Having a central dispatch method (such as our actionPerformed ) is not a nice structure
at all. We essentially make every separate item call a single method, only to write tedious
code in that method to call separate methods for every item from there. This is annoying
in maintenance terms (for every additional menu item we have to add a new if statement
in actionPerformed ); it also seems a waste of effort. It would be much nicer if we could
make every menu item call a separate method directly.
In the next section, we introduce a new language construct that allows us to do just that.
Inner classes
To solve the problems with centralized event dispatch mentioned above, we use a new construct
that we have not discussed before: inner classes . Inner classes are classes that are declared tex-
tually inside another class:
class EnclosingClass
class InnerClass
Search WWH ::

Custom Search