// DrawCenteredString.java import java.awt.*; import javax.swing.*; public class DrawCenteredString extends JApplet { public void drawCenteredString(Graphics page, String s, int x, int y, int width, int height) { // Find the size of string s in the font of the Graphics context "page" FontMetrics fm = page.getFontMetrics(page.getFont()); java.awt.geom.Rectangle2D rect = fm.getStringBounds(s, page); int textHeight = (int)(rect.getHeight()); int textWidth = (int)(rect.getWidth()); // Center text horizontally and vertically within provided rectangular bounds int textX = x + (width - textWidth)/2; int textY = y + (height - textHeight)/2 + fm.getAscent(); page.drawString(s, textX, textY); } public void paint(Graphics page) { // get the dimensions of the draw area int width = this.getWidth(); int height = this.getHeight(); // clear the background page.setColor(Color.white); page.fillRect(0,0,width,height); // center a string in a box int boxX = 10, boxY = 20, boxWidth = 250, boxHeight = 100; page.setColor(Color.darkGray); page.fillRect(boxX,boxY,boxWidth,boxHeight); page.setFont(new Font("SansSerif",Font.BOLD|Font.ITALIC,32)); page.setColor(Color.orange); drawCenteredString(page,"This is a test",boxX,boxY,boxWidth,boxHeight); } public void init() { setBackground(Color.white); } //////////////////////////////////////////// // Main (applet wrapper) //////////////////////////////////////////// public static void main(String[] args) { DrawCenteredString applet = new DrawCenteredString(); applet.init(); final JFrame frame = new JFrame("DrawCenteredString"); frame.getContentPane().add(applet); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setSize(400,400); frame.show(); } }