Java Reference
In-Depth Information
You can also test and compare
Rectangle
objects in various ways with the following methods:
Method
Description
boolean
isEmpty()
Returns
true
if the
width
and
height
members of the
current
Rectangle
object are zero, and
false
otherwise.
boolean
equals(
Object
rect)
Returns
true
if the
Rectangle
object passed as an argument
is equal to the current
Rectangle
object, and returns
false
otherwise.
The two rectangles will be equal if they are at the same
position and have the same width and height. If the argument
is not a
Rectangle
object,
false
is returned.
boolean
intersects(
Rectangle
rect)
Returns
true
if the current
Rectangle
object intersects the
Rectangle
object passed as an argument, and
false
otherwise.
boolean
contains(
Point
p)
Returns
true
if the current
Rectangle
object encloses the
Point
argument
p
, and
false
otherwise.
boolean
contains(
int
x,
int
y)
Returns
true
if the current
Rectangle
object encloses the
point (
x
,
y
), and
false
otherwise.
All of these will be useful when dealing with the contents of a Java window. You will then be dealing
with points and rectangles describing the contents drawn in the window. For example, you might want
to enable the user of your program to select some geometric shape from among those displayed on the
screen, in order to work with it. You could use the
contains()
method to check whether the point
corresponding to the current cursor position is within any of the
Rectangle
objects that enclose each
of the circles, lines, or whatever is displayed in the window. Then you can decide which of the objects
displayed on the screen the user wants to choose.
There are other classes defining rectangles that we shall meet when we start drawing in a window.
Visual Characteristics of a Component
Two things determine the visual appearance of a component: the representation of the component
created by the Java code in the component class that is executed when the component is displayed, and
whatever you draw on the component. You can draw on a
Component
object by implementing its
paint()
method. We used this method in Chapter 1 to output the text for our applet. The
paint()
method is called automatically when the component needs to be drawn.
The need to draw a component can arise quite often for a variety of reasons - for example, your
program may request that the area that the component occupies should be redrawn, or the user may
resize the window containing the component. Your implementation of this method must include code to
generate whatever you want drawn within the
Component
object. Note that the component itself - the
JButton
or
JFrame
or whatever, will be drawn for you. You only need to override the
paint()
method for anything additional that you want to draw on it. We will be overriding the
paint()
method in Chapter 17 to draw in a window, so we will leave further discussion of it until then.