Java Reference
In-Depth Information
0
10
20
30
40
50
60
70
80
90
100
0
10
20
20
10
30
10
40
20
50
60
70
Figure 5.1 The effect of the commands
drawLine(10,20,30,10)
,
drawRect(40,25,
20,10)
and
drawOval(80,40,10,20).
The dotted lines and the dimensions do not ap-
pear in the graphic. The bounding rectangle for the oval is shown as a dotted line
drawString(text,xleft,ybottom)
draws the string
text
. The lower left corner
of the bounding rectangle of the text is at (
xleft, ybottom
). This is the
reference
point
.
fillRect
draws a filled rectangle using the current colour, otherwise like
drawRect
.
fillOval
draws a filled ellipse using the current colour, otherwise like
drawOval
.
setColor(col)
sets the colour of the drawing to
col
. This colour is used until the
setColor
command is used again.
■
5.3
A simple graphical application
Our application is only to demonstrate the use of the graphic commands inside
paintComponent
.Asthere is no user interaction that changes the drawing,
we do not need a model or control part. In the example we derive a class
SimpleGraphicsPanel
from
JPanel
.Inthe constructor we set the background
to white (it is normally grey) and set the size to 300
300 pixels. Then method
paintComponent
is overridden. As explained above, we first make a call to the
original
paintComponent
method. Then follow a number of graphics commands
which set the drawing colour and draw various shapes and a string. The com-
mands are provided by the
Graphics
class of AWT and thus have the syntax
g.drawSomething
where
g
is an instance of
Graphics
. Now whenever the panel
is redrawn these commands are executed and the graphical objects are displayed.
Note that drawing a filled object with the background colour makes parts of other
objects 'disappear'. In the example a white oval partly covers a cyan coloured
one.
×
Search WWH ::
Custom Search