Java Reference
In-Depth Information
Painting with a Graphics Object
Problem
You want to draw something on the screen.
Solution
Write a
Component
subclass; in your
paint()
method, use the provided
Graphics
object's
drawing methods:
public
public class
class
PaintDemo
PaintDemo
extends
extends
Component
{
private
private static
static final
final
long
long
serialVersionUID
= -
5595189404659801913L
;
int
int
rectX
=
20
,
rectY
=
30
;
int
int
rectWidth
=
50
,
rectHeight
=
50
;
/**
* Component subclasses can override paint(), but
* JComponent subclasses should normally use paintComponent()
* instead, to avoid clobbering border painting and the like.
*/
@Override
public
public
void
void
paint
(
Graphics g
) {
g
.
setColor
(
Color
.
red
);
g
.
fillRect
(
rectX
,
rectY
,
rectWidth
,
rectHeight
);
}
@Override
public
public
Dimension
getPreferredSize
() {
return
return new
new
Dimension
(
100
,
100
);
}
}
Discussion
The
Graphics
class has a large set of drawing primitives. Each shape—
Rect
(angle),
Arc
,
Ellipse
, and
Polygon
—has a draw method (draws just the outline) and a fill method (fills
inside the outline). You don't need both, unless you want the outline and the interior (fill) of
a shape to be different colors. The method
drawString()
and its relatives let you print text