Java Reference
In-Depth Information
Font
objects represent the name, style, and point size of a font.
A
Font
object is created by sending three arguments to its constructor:
The font's name
n
The font's style
n
The font's point size
n
The name of the font can be the logical name of a font, such as Arial, Courier New,
Garamond, or Kaiser. If the font is present on the system on which the Java program is
running, it will be used. If the font is not present, the default font will be used.
The name also can be one of five generic fonts: Dialog, DialogInput, Monospaced,
SanSerif, or Serif. These fonts can be used to specify the kind of font to use without
requiring a specific font. This is often a better choice because some font families might
not be present on all implementations of Java.
Three
Font
styles can be selected by using static class variables:
PLAIN
,
BOLD
, and
ITALIC
. These constants are integers, and you can add them to combine effects.
The following statement creates a 24-point Dialog font that is bold and italicized:
Font f = new Font(“Dialog”, Font.BOLD + Font.ITALIC, 24);
After you have created a font, you can use it by calling the
setFont(
Font
)
method of the
Graphics2D
class with the font as the method argument.
The
setFont()
method sets the font used for subsequent calls to the
drawString()
method on the same
Graphics2D
object. You can call it again later to change the font and
draw more text.
The following
paintComponent()
method creates a new
Font
object, sets the current font
to that object, and draws the string “I'm very font of you” at the coordinate 10, 100:
public void paintComponent(Graphics comp) {
Graphics2D comp2D = (Graphics2D)comp;
Font f = new Font(“Arial Narrow”, Font.PLAIN, 72);
comp2D.setFont(f);
comp2D.drawString(“I'm very font of you”, 10, 100);
13
}
Java programs can ensure that a font is available by including it with the program and
loading it from a file. This technique requires the
Font
class method
createFont(
int
,
InputStream
)
, which returns a
Font
object representing that font.