Lesson 4 | Drawing text |
Objective | Draw graphical text. |
Drawing Graphical Text in Java
In applets and graphical Java applications, text is drawn as graphics. The benefit to drawing text as graphics is that you can use different kinds of fonts, as well as different font sizes and styles. The Font class encapsulates these text properties, and is the basis for the font attribute in the Graphics class. The constructor for the Font class follows:
public Font(String name, int style, int size)
The parameters to this constructor specify the string name of the font, the style of the font (Font.BOLD, Font.ITALIC, and/or Font.PLAIN), and the integer font size. The following standard font names are safe to use
on most systems: Serif, Monospaced, and SansSerif.
The following code creates a Font object:
Font f = new Font("Serif", Font.ITALIC, 18);
This code creates an italic, 18-point Serif font. To draw text in this font, you must first select the font into a graphics context using the setFont() method:
g.setFont(f);
You can then use the drawString() method to draw a string of text:
g.drawString("So little time, so little to do.",20, 20);
The parameters to the drawString() method specify the string to be drawn, along with the X and Y position of the string. The X position is the left edge of the text, while the Y position is the bottom of the text.
Drawing Text - Exercise
Click the Exercise link below to draw text.
Drawing Text - Exercise
Awt Graphics - Quiz
Click the Quiz link below to test your knowledge of drawing graphics with the Java AWT.
AWT Graphics - Quiz