Question

Running the following code:

import java.awt.Font;
import java.awt.FontMetrics;

public class MetricsTest {

    public static void main(String[] args) {
                Font myFontTest=new Font("Arial", Font.PLAIN, 11);
                FontMetrics metrics  = new FontMetrics(myFontTest) {};
                int characterWidth=metrics.charWidth('A');
                System.out.println(characterWidth);
    }
}

produces this error:

Exception in thread "main" java.lang.StackOverflowError

at java.awt.FontMetrics.getWidths(FontMetrics.java:430)

at java.awt.FontMetrics.charWidth(FontMetrics.java:333)

at java.awt.FontMetrics.getWidths(FontMetrics.java:430)

at java.awt.FontMetrics.charWidth(FontMetrics.java:333)

at java.awt.FontMetrics.getWidths(FontMetrics.java:430)

and so on....

Why?

Was it helpful?

Solution 2

Here is a solution:
(see comment by user Boris the Spider) on my original post)

import java.awt.Canvas;
import java.awt.Font;
import java.awt.FontMetrics;

public class MetricsTest {

    public static void main(String[] args) {
                Font myFontTest=new Font("Arial", Font.PLAIN, 11);
                Canvas c = new Canvas();
                FontMetrics fm = c.getFontMetrics(myFontTest);
                int characterWidth=fm.charWidth('A');
                System.out.println(characterWidth);

    }

}

OTHER TIPS

From the doc:

Note to subclassers: Since many of these methods form closed, mutually recursive loops, you must take care that you implement at least one of the methods in each such loop to prevent infinite recursion when your subclass is used. In particular, the following is the minimal suggested set of methods to override in order to ensure correctness and prevent infinite recursion (though other subsets are equally feasible):

This:

FontMetrics metrics  = new FontMetrics(myFontTest) {};

defines a subclass without any methods overridden, hence the behaviour you're seeing.

Rewrite your code as follows :

try {
    Font myFontTest=new Font("Arial", Font.PLAIN, 11);
    Frame f = new Frame();
    //FontMetrics metrics = f.getToolkit().getFontMetrics(myFontTest);      
    FontMetrics metrics = Toolkit.getDefaultToolkit().getFontMetrics(myFontTest);

    int characterWidth=metrics.charWidth('A');
    System.out.println(characterWidth);
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top