The method FontMetrics.stringWidthdoes just that - it will return the width in pixels for the given one String.
Can be obtained FontMetricsfrom the Graphicsobject getFontMetrics.
For example:
g.setFont(new Font("Serif", Font.BOLD, 24));
int width = g.getFontMetrics().stringWidth("Hello World!");
System.out.println(width);
The result is:
135
source
share