694 Part II: The Java Library
// Advance to next line.
void nextLine(String s, Graphics g) {
FontMetrics fm = g.getFontMetrics();
curY += fm.getHeight(); // advance to next line
curX = 0;
g.drawString(s, curX, curY);
curX = fm.stringWidth(s); // advance to end of line
}
// Display on same line.
void sameLine(String s, Graphics g) {
FontMetrics fm = g.getFontMetrics();
g.drawString(s, curX, curY);
curX += fm.stringWidth(s); // advance to end of line
}
}
Sample output from this program is shown here:
Centering Text
Here is an example that centers text, left to right, top to bottom, in a window. It obtains the
ascent, descent, and width of the string and computes the position at which it must be displayed
to be centered.
// Center text.
import java.applet.*;
import java.awt.*;
/*
<applet code="CenterText" width=200 height=100>
</applet>
*/
public class CenterText extends Applet {
final Font f = new Font("SansSerif", Font.BOLD, 18);
public void paint(Graphics g) {
Dimension d = this.getSize();
g.setColor(Color.white);
g.fillRect(0, 0, d.width,d.height);
g.setColor(Color.black);