Creating and Selecting a Font
To select a new font, you must first construct a Font object that describes that font. One Font
constructor has this general form:
Font(String fontName, int fontStyle, int pointSize)
Here, fontName specifies the name of the desired font. The name can be specified using either
the logical or face name. All Java environments will support the following fonts: Dialog,
DialogInput, Sans Serif, Serif, and Monospaced. Dialog is the font used by your system's dialog
boxes. Dialog is also the default if you don't explicitly set a font. You can also use any other
fonts supported by your particular environment, but be careful--these other fonts may not
be universally available.
The style of the font is specified by fontStyle. It may consist of one or more of these three
constants: Font.PLAIN, Font.BOLD, and Font.ITALIC. To combine styles, OR them together.
For example, Font.BOLD | Font.ITALIC specifies a bold, italics style.
The size, in points, of the font is specified by pointSize.
To use a font that you have created, you must select it using setFont( ), which is defined
by Component. It has this general form:
void setFont(Font fontObj)
Here, fontObj is the object that contains the desired font.
The following program outputs a sample of each standard font. Each time you click the
mouse within its window, a new font is selected and its name is displayed.
// Show fonts.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="SampleFonts" width=200 height=100>
</applet>
*/
public class SampleFonts extends Applet {
int next = 0;
Font f;
String msg;
public void init() {
f = new Font("Dialog", Font.PLAIN, 12);
msg = "Dialog";
setFont(f);
addMouseListener(new MyMouseAdapter(this));
}
public void paint(Graphics g) {
g.drawString(msg, 4, 20);
}
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home