ptg7068951
328 HOUR 23:Creating Java2D Graphics
When you have a font, you callthe Graphics2Dcomponent’s
setFont(Font)method to designate it as the current font. All subsequent
drawing operations use that font until another one is set. Statements in the
following example create a “Comic Sans” font object and designate it as
the current font before drawing text:
public voidpaintComponent(Graphics comp) {
Graphics2D comp2D = (Graphics2D) comp;
Font font = new Font(“Comic Sans”, Font.BOLD, 15);
comp2D.setFont(font);
comp2D.drawString(“Potrzebie!”, 5, 50);
}
Java supports antialiasingto draw fonts and graphics more smoothly and
less blocky in appearance. To enable this functionality, you must set a ren-
dering hint in Swing. AGraphics2Dobject has a setRenderingHint(int,
int)method that takes two arguments:
. The key of the rendering hint
. The value to associate with that key
These values are class variables in the RenderingHintsclass of java.awt.
To activate antialiasing, call setRenderingHint()with two arguments:
comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
The comp2Dobject in this example is the Graphics2Dobject that represents
a container’s drawing environment.
Using the Color Class
Colors in Java are represented by the Colorclass, which includes the fol-
lowing constants as class variables: black, blue, cyan, darkGray, gray,
green, lightGray, magenta, orange, pink, red, white, and yellow.
In a container, you can set the background color of the component using
these constants by calling the setBackground(Color)method like this:
setBackground(Color.orange);
The current color, like the current font, must be set before drawing takes
place using the setColor(Color)method. The following code includes a
statement to set the current color to orange and draw text in that color: