Fonts
The Font for a Component can be set. If the Component is a Container, then all components added to that Container will assume the Container's Font. Font is a class that simply stores information about a class such as its font name, weight, and point size.
To get the list of available fonts, ask for the current Toolkit (the class that maps AWT to the underlying native windowing toolkit) and then ask the toolkit for the font list:
String[] fontList = Toolkit.getDefaultToolkit().getFontList();
Creating a Font is simple:
Font myFont = new Font("Helvetica", Font.BOLD, 12);
You can either set the Font of a Component or a Graphics context; for example, here is an applet that draws some text in Helvetica:
Corresponding source code:
import java.awt.*;
public class FontTest extends java.applet.Applet {
public void paint(Graphics g) {
Font f = new Font("Helvetica", Font.BOLD, 16);
g.setFont(f);
g.drawString("Helvetica 16 point Bold", 10, 30);
}
}
You can ask a Font for its width and height in pixels via font metrics:
Font f = new Font("Helvetica", Font.BOLD, 16);
FontMetrics fm = getFontMetrics(f);
int h = fm.getHeight();
// how wide is z in this font?
int w = fm.getWidth('z');
Related exercise(s):
You have reached the end of the course notes. You can proceed to the Exercises.
|