Home
JAVA APPLET
Centering Text
Here is an example that centers text, left to right, top to bottom, in a window
import java.applet.*; import java.awt.*; public class centeringtext extends Applet { final Font f= new Font("ARIAL",Font.BOLD,12); 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); g.setFont(f); drawCenteredString("This is Centered",d.width,d.height,g); g.drawRect(0,0,d.width-1,d.height-1); } public void drawCenteredString(String s,int w, int h, Graphics g) { FontMetrics fm = g.getFontMetrics(); int x = (w-fm.stringWidth(s))/2; int y = (fm.getAscent()+(h-(fm.getAscent() + fm.getDescent()))/2); g.drawString(s,x,y); } }
Previous
Next