Java – How to visually center a specific string (not just a font) in a rectangle

While I muck about with TextLayout, you could just use the Graphics context’s FontMetrics, for example… import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.Rectangle2D; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class LayoutText { public static void main(String[] args) … Read more

Java center text in rectangle

I’ve used this to center text on a JPanel Graphics2D g2d = (Graphics2D) g; FontMetrics fm = g2d.getFontMetrics(); Rectangle2D r = fm.getStringBounds(stringTime, g2d); int x = (this.getWidth() – (int) r.getWidth()) / 2; int y = (this.getHeight() – (int) r.getHeight()) / 2 + fm.getAscent(); g.drawString(stringTime, x, y);