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.
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( ) { ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.