Getting FontMetrics StackOverflowError

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);
    }
}

causes this error:

Exception in thread "main" java.lang.StackOverflowError

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

in java.awt.FontMetrics.charWidth (FontMetrics.javahaps33)

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

in java.awt.FontMetrics.charWidth (FontMetrics.javahaps33)

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

etc....

Why?

+4
source share
3 answers

Here is the solution:
(see the comment by Boris the Spider) in 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);

    }

}
+1
source

From the doc :

: , , , , , . , ( ):

:

FontMetrics metrics  = new FontMetrics(myFontTest) {};

, , , .

+3

Rewrite the 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();
}
+1
source

Source: https://habr.com/ru/post/1530063/


All Articles