Java Reference
In-Depth Information
Figure 12-1. CompRunner showing DrawStringDemo2 (left) and javax.swing.JTree (right)
Because little of this relates to the material in this chapter, I don't show the source for
Com-
pRunner
; however, it's included in the
gui
directory of the
javasrc
code examples for the
book.
Drawing Text
Problem
You need to draw text in a component.
Solution
Simply call the
drawString()
method in the
Graphics
class:
public
public class
class
DrawStringDemo
DrawStringDemo
extends
extends
JComponent
{
private
private static
static final
final
long
long
serialVersionUID
= -
7199469682507443122L
;
int
int
textX
=
10
,
textY
=
20
;
@Override
public
public
void
void
paintComponent
(
Graphics g
) {
g
.
drawString
(
"Hello Java"
,
textX
,
textY
);
}
public
public
Dimension
getPreferredSize
() {
return
return new
new
Dimension
(
100
,
100
);