Because this topic can be confusing and it can also be done different ways (FontMetrics vs LineMetrics), I created this example for you to use as a reference. Some of this could be simplified with helper methods. Also, I don't do much of this so there may also be more efficient ways.
Regards,
Jim
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;
public class HelloWorld extends JPanel {
JFrame frame = new JFrame("Hello World");
Font font = new Font("Arial", Font.PLAIN, 48);
String firstLine = "Hello";
String secondLine = "World";
FontRenderContext frc = new FontRenderContext(null, true, true);
LineMetrics lm = font.getLineMetrics("Hello World", frc);
public static void main(String[] args) {
// schedule for the EDT
// the method start() just gets us out of static context
SwingUtilities.invokeLater(() -> new HelloWorld().start());
}
public void start() {
// basic bookkeeping to create a panel in a frame and display
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400, (int) (400 * .618)));
setBackground(Color.white);
frame.add(this);
frame.pack();
frame.setLocationRelativeTo(null); // center on screen
frame.setVisible(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// smooth out the graphics
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setFont(font);
// Center in the panel. I guess for the height but
// the horizontal centering was computed.
int h = (int) lm.getHeight();
TextLayout tm = new TextLayout("Hello", font, frc);
Rectangle2D rect = tm.getBounds();
float w = (float) rect.getWidth();
g2d.drawString("Hello", (400 - w) / 2, 100);
tm = new TextLayout("World", font, frc);
rect = tm.getBounds();
w = (float) rect.getWidth();
g2d.drawString("World", (400 - w) / 2, 100 + h);
}
}