+ FontMetrics fm1 = g2d.getFontMetrics();
+ float x1 = rect.x + (float)(rect.width - fm1.stringWidth(text)) / 2;
+ float y1 = rect.y + (float)(rect.height - fm1.getHeight()) / 2 + fm1.getAscent();
+ g2d.drawString(text, x1, y1);
+
+ g2d.setFont(oldFont);
+ }
+
+ private static Font scaleFontToFit(String text, int width, Graphics2D g2d, Font pFont) {
+ float fontSize = pFont.getSize();
+ float fWidth = g2d.getFontMetrics(pFont).stringWidth(text);
+ if(fWidth <= width) {
+ return pFont;
+ }
+ fontSize = ((float)width / fWidth) * fontSize;
+ return pFont.deriveFont(fontSize);