Java Reference
In-Depth Information
We need to add the following parts:
We create a new menu (class JMenu ) named Filter and add it to the menu bar.
We create three menu items (class JMenuItem ) named Darker , Lighter , and Threshold , and
add them to our filter menu.
To each menu item, we add an action listener, using the code idiom for anonymous classes
that we discussed for the other menu items. The action listeners should call the methods
makeDarker , makeLighter , and threshold , respectively.
After we have added the menus and created the (initially empty) methods to handle the filter
functions, we need to implement each filter.
The simplest kinds of filters involve iterating over the image and making a change of some sort
to the color of each pixel. A pattern for this process is shown in Code 11.6. More-complicated
filters might use the values of neighboring pixels to adjust a pixel's value.
Exercise 11.23 Add the new menu and the menu items to your version of the image-
viewer0-4 project, as described here. In order to add the action listeners, you need to create
the three methods makeDarker , makeLighter , and threshold as private methods in
your ImageViewer class. They all have a void return type and take no parameters. These
methods can initially have empty bodies, or they could simply print out that they have been
Code 11.6
Pattern for a simple
filtering process
int height = getHeight();
int width = getWidth();
for ( int y = 0; y < height; y++) {
for ( int x = 0; x < width; x++) {
Color pixel = getPixel(x, y);
alter the pixel's color value;
setPixel(x, y, pixel);
The filter function itself operates on the image, so following responsibility-driven de-
sign guidelines, it should be implemented in the OFImage class. On the other hand, han-
dling the menu invocation also includes some GUI-related code (for instance, we have to
check whether an image is open at all when we invoke the filter), and this belongs in the
ImageViewer class.
As a result of this reasoning, we create two methods, one in ImageViewer and one in
OFImage , to share the work (Code 11.7 and Code 11.8). We can see that the makeDarker
method in ImageViewer contains the part of the task that is related to the GUI (checking
Search WWH ::

Custom Search