Java Reference
In-Depth Information
All pixel values are integers; you can't use decimal numbers to display something at a
position between two integer values.
Figure 13.1 depicts Java's graphical coordinate system visually, with the origin at 0, 0.
Two of the points of a rectangle are at 20, 20 and 60, 60.
FIGURE 13.1
The Java graphics
coordinate system.
0,0
+X
20,20
60,60
+Y
Text is the easiest thing to draw on an interface component.
To draw text, call a
Graphics2D
object's
drawString()
method with three arguments:
The
String
to display
n
The x coordinate where it should be displayed
n
The y coordinate where it should be displayed
n
The x,y coordinate used in the
drawString()
method represent the pixel at the lower-left
corner of the string.
The following
paintComponent()
method draws the string “Free the bound periodicals”
at the coordinate 22, 100:
public void paintComponent(Graphics comp) {
Graphics2D comp2D = (Graphics2D)comp;
comp2D.drawString(“Free the bound periodicals”, 22, 100);
}
The preceding example uses a default font. To use a different font, you must create an
object of the
Font
class in the
java.awt
package.