Java Reference
In-Depth Information
Finding Information About a Font
To make text look good in a graphical user interface, you often must figure out how
much space the text is taking up on an interface component.
The FontMetrics class in the java.awt package provides methods to determine the size
of the characters being displayed with a specified font, which can be used for things such
as formatting and centering text.
The FontMetrics class can be used for detailed information about the current font, such
as the width or height of characters it can display.
To use this class's methods, a FontMetrics object must be created using the
getFontMetrics() method. The method takes a single argument: a Font object.
Table 13.1 shows some of the information you can find using font metrics. All these
methods should be called on a FontMetrics object.
TABLE 13.1
Font Metrics Methods
Method Name
Action
Given a string, returns the full width of that string in pixels
stringWidth( String )
Given a character, returns the width of that character
charWidth( char )
Returns the total height of the font
getHeight()
Listing 13.1 shows how the Font and FontMetrics classes can be used. The TextFrame
application displays a string at the center of a frame, using font metrics to measure the
string's width using the selected font.
LISTING 13.1
The Full Text of TextFrame.java
1: import java.awt.*;
2: import java.awt.event.*;
3: import javax.swing.*;
4:
5: public class TextFrame extends JFrame {
6: public TextFrame(String text, String fontName) {
7: super(“Show Font”);
8: setSize(425, 150);
9: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
10: TextFramePanel sf = new TextFramePanel(text, fontName);
11: add(sf);
12: setVisible(true);
13: }
14:
13
 
Search WWH ::




Custom Search