Java Reference
In-Depth Information
super
. paintComponent(g) ;
Graphics2D g2 = (Graphics2D) g ;
for
(MyShape s
:
shapes )
{
s . drawShape(g2) ;
}
}
}
class
MyShape
{
private
ArrayList
<
Point2D
>
points =
new
ArrayList
<>
() ;
public
MyShape ( )
{
}
public
MyShape( Point2D point )
{
points .add(point) ;
}
public void
addPoint(Point2D point )
{
points .add(point) ;
}
public void
drawShape(Graphics2D g)
{
g. setPaint(Color .RED) ;
if
(points.size() == 0)
{
return
;
}
Point2D start = points .get(0) ;
for
(Point2D end : points )
{
g.draw(
new
Line2D.Double(start , end)) ;
start = end;
}
}
}
Of course, this program must be put in a file with the name
DrawingGame.java
.Re-
member that we must have a single class of type
public
in every Java file that matches the
name of the file.
10.3.3 Menu Listeners
Drawing using the red color is nice. However, what if we want to create a multi-colored
drawing? We will show how to do this next. We will allow the user to select the color of his
or her drawing using a menu.
Every window can have at most one menu bar. The menu bar can have one
or more menus. Every menu can have several menu items. An event listener
of type
ActionListener
can be registered with every menu item. The method
actionPerformed
of the listener will be called when the menu item is selected.
Creating a menu is pretty straightforward. Here is the code to add a menu to the drawing
game.
class
MyFrame
extends
JFrame
{