Java Reference
In-Depth Information
The program
FreeDrawApplet
uses small circles to draw lines. Because there is no GUI
component we can use, we created the
class
ColorCircle
. This class has two
private
members
x
and
y
of the type
int
. The point (
x
,
y
) specifies the center of the
circle, and the radius of the circle is fixed at 10 pixels. In addition to the methods to set
the values of
x
and
y
, the
class
ColorCircle
has only two other methods:
paint
and
isSelected
. The
paint
method draws a filled circle of radius 10 at the point (
x
,
y
).
The method
isSelected
returns
true
if and only if (
iXcoord
,
iYcoord
) lies inside a
20-by-20 square with the point (
x
,
y
) as the center. We use this method to check
whether the mouse is at, say, (
iXcoord
,
iYcoord
) on the circle with the center (
x
,
y
).
Note that because
ColorCircle
is not a GUI component, it can generate any event.
Therefore, any time a
mouseDragged
event is generated, we must check whether the
mouse is on any of the circles. We do so using the following
for
loop:
for
(
int
i = 0; i < NUM_CIRCLES; i++)
if
(myGraph[i].selected(iX, iY))
{
myGraph[i].setX(iX);
myGraph[i].setY(iY);
break
;
}
Note that if a
mouseDragged
event occurs on a
ColorCircle
object, the preceding
for
loop sets the current mouse position as the new center of the
ColorCircle
object. This,
in effect, moves the
ColorCircle
object. By continually moving a
ColorCircle
object,
we create a line.
PROGRAMMING EXAMPLE:
Java Kiosk
In this programming example, we design a program that simulates a fast food kiosk.
The program displays a menu similar to one you might find in a fast food restaurant.
The user makes a selection and then presses a
JButton
to mark the end of the
selection process. The program then calculates and displays the bill. A sample output
is shown in Figure 12-25.
1
2
Search WWH ::
Custom Search