Java Reference
In-Depth Information
}
}
}
class
MyShape
{
private
ArrayList
<
Point2D
>
points =
new
ArrayList
<
Point2D
>
() ;
private
Color color ;
public
MyShape ( )
{
color = Color.RED;
}
public
MyShape( Point2D point , Color co l o r )
{
this
. color = color ;
points .add(point) ;
}
public void
addPoint(Point2D point )
{
points .add(point) ;
}
public void
drawShape(Graphics2D g)
{
g. setPaint(color) ;
if
(points.size() == 0)
{
return
;
}
Point2D start = points .get(0) ;
for
(Point2D end : points )
{
g.draw(
new
Line2D.Double(start , end)) ;
start = end;
}
}
}
Note that the
ColorListener
class is an inner class for the
MyFrame
class. Using anony-
mous local classes is not the best solution here because the class is referenced three times
to create the three color listeners. The constructor of the
ColorListener
class simply saves
the color. When the user selects that they want to use the color, the
actionPerformed
method is executed, which in turn changes the current drawing color in the
MyPanel
class.
When a new shape is created, the current color is passed as a parameter to the shape. When
a shape is drawn, the brush is first set to this color. To accomplish this, we have added the
variable
color
to the
MyShape
class. The constructor of the
MyShape
class is also updated
to set the initial value for the color of the shape.
10.4 Multicasting
In our drawing game, we created three event listeners and associated them with the
three menu items. It turns out that one can associate multiple event listeners with the
same event source. When the event occurs, the event source will multicast the event to
all the event listeners that are registered with the event source. Note that Java provides
no guarantees on the order in which the event listeners will be contacted. In order to
demonstrate the multicasting mechanism, we will create a simple application that creates
and destroys windows using a menu. We will have a single main window with two menu