Java Reference
In-Depth Information
Code 11.13
continued
Adding a collection
of filters
public
ImageViewer()
{
filters = createFilters();
...
}
private
List<Filter> createFilters()
{
List<Filter> filterList =
new
ArrayList<Filter>();
filterList.add(
new
DarkerFilter(
"Darker"
));
filterList.add(
new
LighterFilter(
"Lighter"
));
filterList.add(
new
ThresholdFilter(
"Threshold"
));
return
filterList;
}
//
Other methods omitted.
}
Once we have this structure in place, we can make the last two necessary changes:
■
We change the code that creates the filter menu items so that it iterates over the filter collec-
tion. For every filter, it creates a menu item and uses the filter's
getName
method to deter-
mine the item's label.
■
Having done this, we can write a generic
applyFilter
method that receives a filter as a
parameter and applies this filter to the current image.
The
imageviewer2-0
project includes a complete implementation of these changes.
Exercise 11.35
Open the
imageviewer2-0
project. Study the code for the new method to
create and apply filters in class
ImageViewer
. Pay special attention to the
makeMenuBar
and
applyFilter
methods. Explain in detail how the creation of the filter menu items and
their activation works. Draw an object diagram. Note, in particular, that the
filter
variable in
makeMenuBar
has been declared as
final
, as discussed in Section 11.4.8. Make sure that
you understand why this is necessary.
Exercise 11.36
What needs to be changed to add a new filter to your image viewer?
Exercise 11.37
Challenge exercise
You might have observed that the
apply
methods of
all of the
Filter
subclasses have a very similar structure: iterate over the whole image and
change the value of each pixel independently of surrounding pixels. It should be possible to iso-
late this duplication in much the same way as we did in creating the
Filter
class.
Create a method in the
Filter
class that iterates over the image and applies a filter-specific
transformation to each individual pixel. Replace the bodies of the
apply
methods in the three
Filter
subclasses with a call to this method, passing the image and an object that can apply
the appropriate transformation.
Search WWH ::
Custom Search