/* * File: CenterText.java * Author: Java, Java, Java, 2E * Description: This Swing application centers a string of * text in its top-level window. When the window is resized * and then closed and reopened, the text is recentered. * Note that it is necessary to clear the window before * repainting it. */ import java.awt.*; import javax.swing.*; public class CenterText extends JFrame { /** * paint() is invoked automatically whenever the frame's * window is resized. It gets a random font and * and the applet's current size, and displays a text string * centered in the applet window. */ public void paint(Graphics g) { String str = "Hello World!"; g.setFont(new Font("Random", Font.PLAIN, 24)); // Create a random font FontMetrics metrics = g.getFontMetrics(); // And get its metrics Dimension d = getSize(); // Get the frame's size g.setColor(getBackground()); g.fillRect(0, 0, d.width, d.height); // Clear the frame g.setColor(Color.black); int x = (d.width - metrics.stringWidth(str)) / 2; // Calculate coordinates int y = (d.height + metrics.getHeight()) / 2; g.drawString(str, x, y); // Draw the string } // paint() /** main() creates the top-level window and sizes and displays it. */ public static void main(String args[]) { CenterText ct = new CenterText(); ct.setSize(400,400); ct.setVisible(true); } // main() } // CenterText