Java AWT FontMetrics get font height and width
import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; class Demo extends JPanel { int curX=0, curY=0; // current position public Demo() { Font f = new Font("SansSerif", Font.PLAIN, 12); setFont(f);/*from w w w. j a v a 2 s . c o m*/ } public void paint(Graphics g) { nextLine("This is on line one.", g); nextLine("This is on line two.", g); sameLine("This is on same line.", g); sameLine("This, too.", g); nextLine("This is on line three.", g); curX = curY = 0; // reset the coordinates for each repaint } // Advance to next line. void nextLine(String s, Graphics g) { FontMetrics fm = g.getFontMetrics(); curY += fm.getHeight(); // advance to next line curX = 0; g.drawString(s, curX, curY); curX = fm.stringWidth(s); // advance to end of line } // Display on same line. void sameLine(String s, Graphics g) { FontMetrics fm = g.getFontMetrics(); g.drawString(s, curX, curY); curX += fm.stringWidth(s); // advance to end of line } } public class Main { public static void main(String[] args) { Demo panel = new Demo(); JFrame application = new JFrame(); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); application.add(panel); application.setSize(250, 250); application.setVisible(true); } }