Java Utililty Methods FontMetrics

List of utility methods to do FontMetrics

Description

The list of methods to do FontMetrics are organized into topic(s).

Method

PointgetCenterOffset(Graphics g, Font f, char ch)
Given a character and its font, calculate the center point offset for that character.
FontMetrics fm = g.getFontMetrics(f);
int xOffset = (int) (fm.charWidth(ch) / 2);
int yOffset = (int) (fm.getAscent() / 2);
return new Point(xOffset, yOffset);
floatgetComponentAverageCharacterWidth(Component component)
Calculates the average character width for the given Component .
FontMetrics metrics = component.getFontMetrics(component.getFont());
int i = 0;
float avgWidth = 0;
for (int width : metrics.getWidths()) {
    avgWidth += width;
    i++;
return avgWidth / i;
...
FontMetricsgetConsoleFontMetrics(Font font)
Returns metrics of given font.
BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
Graphics2D g = (Graphics2D) graphics;
g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g.setFont(font);
FontMetrics metrics = g.getFontMetrics();
return metrics;
intgetLineBreakIndex(Graphics g, String text, int index, double maxWidth)
Computes the index of the next line break.
FontMetrics fm = g.getFontMetrics();
int i = index;
double width = 0.0;
while (i < text.length()) {
    int codePoint = text.codePointAt(i);
    width += fm.charWidth(codePoint);
    if (width >= maxWidth) { 
        break;
...
intgetLineHeight(Component c, int defaultHeight)
get Line Height
Font f = c == null ? null : c.getFont();
if (f == null) {
    return defaultHeight;
FontMetrics fm = c.getFontMetrics(f);
float h = fm.getHeight();
h += fm.getDescent();
return (int) h;
...
intgetLineHeight(Component c, int defaultHeight)
Gets the line height for the font for the component
Font f = c == null ? null : c.getFont();
if (f == null) {
    return defaultHeight;
FontMetrics fm = c.getFontMetrics(f);
float h = fm.getHeight();
h += fm.getDescent();
return (int) h;
...
intgetLineHeight(Component component, int count)
get Line Height
return getFontMetrics(component).getHeight() * count;
doublegetLineHeight(FontMetrics fm)
get Line Height
return fm.getMaxDescent() + fm.getMaxAscent();
intgetLongestStringWidth(FontMetrics fm, String[] theStrings)
Method getLongestStringWidth.
int longestWidth = 0;
for (int i = 0; i < theStrings.length; i++) {
    if (theStrings[i] != null && !theStrings[i].equalsIgnoreCase("")) {
        if (fm.stringWidth(theStrings[i]) > longestWidth) {
            longestWidth = fm.stringWidth(theStrings[i]);
return longestWidth;
intgetMaxFittingFontSize(Graphics g, Font font, String string, Dimension size)
Calculates the largest size of the given font for which the given string will fit into the given size.
return getMaxFittingFontSize(g, font, string, size.width, size.height);