Using Fonts with Applets
First I will show you how to display text onto your applet. You can display text in a wide variety of ways in Java. In Java, you can create multiple fonts that allow you to display text in different ways.
In Java a font is an instance of a typeface that specifies the following information:
- The typeface used to display the font
- The size of the font
- Special effects, such as italics or bolding
I will now show you a simple Java application that creates a font and makes use of it. This program can be seen in Listing 1.2.
Listing 1.2: An Applet that uses a Font (FontApplet.java)
import java.awt.*;
import java.applet.*;
public class FontApplet extends Applet
{
public void paint(Graphics g)
{
Font font = new Font("Arial",Font.BOLD,30);
g.setFont(font);
FontMetrics fm = g.getFontMetrics();
g.setColor(Color.BLACK);
// first set y to the first line that will be on-screen
int y = fm.getHeight();
// draw a line of text there
g.drawString("Hello World",10,y);
}
}You can see the output from this program in Figure 1.2.
Figure 1.2: An applet that uses fonts
The font is created with the following line of code.
Font font = new Font("Arial",Font.BOLD,30);The above line of code creates a font that use the typeface "Arial". The font will be 30 points tall (normal news print is 10 points tall). The font will also be bold.
Once the font has been created, it must be handed to the "Graphics" object to be used for text display. You can create multiple fonts and select which font to use by calling the "setFont" method on the "Graphics" object. This can be seen here.
g.setFont(font);
Once the font has been selected any text that is displayed with "drawString" will be displayed using the new font.
g.drawString("Hello World",10,y);As you can see the above "drawstring" method is passed three parameters. The first parameter specifies the text that is to be displayed. Next is the x coordinate to display the text at. Finally, the y coordinate is specified. You will notice that the y coordinate is a variable. This is because we had to query the graphics object to see how tall the text will be.
In the next section I will show you how you can measure the sizes of the fonts to properly display them.



