📄 fontmetricsdemo.java
字号:
// FontMetricsDemo.java
import java.awt.*;
import java.applet.Applet;
public class FontMetricsDemo extends Applet
{
String the = "The ";
String [] msgs =
{
" method is handy for centering text.",
" method is handy for spacing between rows of text.",
" method returns the maximum ascent of any character.",
" method returns the maximum descent of any character."
};
String [] methods =
{
"stringWidth",
"getHeight",
"getMaxAscent",
"getMaxDescent"
};
public void paint (Graphics g)
{
// Create a Bold Serif font, establish this font
// as the graphics context font, and obtain font
// metrics for this font.
Font f1 = new Font ("Serif", Font.BOLD, 12);
g.setFont (f1);
FontMetrics fm = g.getFontMetrics ();
// Create an array to hold method name widths.
int [] wMethod = new int [methods.length];
// For each method name in the methods array,
// compute its width (in pixels) when displayed
// using the Bold font.
for (int i = 0; i < wMethod.length; i++)
wMethod [i] = fm.stringWidth (methods [i]);
// Establish a Plain Serif font as the graphics
// context font.
Font f2 = new Font ("Serif", Font.PLAIN, 12);
g.setFont (f2);
fm = g.getFontMetrics ();
// Calculate the width (in pixels) of the string
// referenced by the, when displayed using Plain
// Serif.
int wThe = fm.stringWidth (the);
// Calculate a width array for all messages.
int [] wMsg = new int [msgs.length];
// Compute each message's display width based on
// Plain Serif.
for (int i = 0; i < wMsg.length; i++)
wMsg [i] = fm.stringWidth (msgs [i]);
// For each message, determine the horizontal
// start position so that the message can be
// horizontally centered. Then, obtain the
// current display row (taking baseline into
// account), and draw the message. Change
// fonts (accordingly) so that method names
// appear in Bold Serif and the rest of the
// text appears in Plain Serif.
for (int i = 0; i < msgs.length; i++)
{
int x = getSize ().width - wThe - wMethod [i] - wMsg [i];
x >>= 1; // A faster way of dividing by 2.
int y = fm.getHeight () * (i + 1);
g.drawString (the, x, y);
x += wThe;
g.setFont (f1);
g.drawString (methods [i], x, y);
x += wMethod [i];
g.setFont (f2);
fm = g.getFontMetrics ();
g.drawString (msgs [i], x, y);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -