문제

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?

도움이 되었습니까?

해결책 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);

    }

}

다른 팁

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();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top