Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Drawing Centered Text in a Component

Problem

You want to draw text neatly centered in a component.

Solution

Measure the width and height of the string in the given font, and subtract it from the width and height of the component. Divide by two, and use this as your drawing location.

Discussion

The program DrawStringDemo2 measures the width and height of a string (see Figure 12-2 for some attributes of the text). The program then subtracts the size of the text from the size of the component, divides this by two, and thereby centers the text in the given component.

Font metrics

Figure 12-2. Font metrics

// file graphics/DrawStringDemo2.java import java.awt.*; public class DrawStringDemo2 extends Component { String message = "Hello Java"; /** Paint is called (by AWT) when it's time to draw the text. */ public void paint(Graphics g) { // Get the current Font, and ask it for its FontMetrics. FontMetrics fm = getFontMetrics(getFont( )); // Use the FontMetrics to get the width of the String. // Subtract this from width, divide by 2, that's our starting point. int textX = (getSize( ).width - fm.stringWidth(message))/2; if (textX<0) // If string too long, start at 0 textX = 0; // Same as above but for the height int textY = (getSize().height - fm.getLeading( ))/2; if (textY<0) textY = 0; // Now draw the text at the computed spot. g.drawString(message, textX, textY); } public Dimension getPreferredSize( ) { ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata