java - 获取 FontMetrics StackOverflowError

标签 java fonts awt stack-overflow fontmetrics

运行以下代码:

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

产生这个错误:

线程“main”中的异常 java.lang.StackOverflowError

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

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

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

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

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

等等....

为什么?

最佳答案

来自 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):

这个:

FontMetrics metrics  = new FontMetrics(myFontTest) {};

定义了一个没有覆盖任何方法的子类,因此出现了您所看到的行为。

关于java - 获取 FontMetrics StackOverflowError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22177948/

相关文章:

java - 使用 sendKeys() 在 Selenium 中上传文件不起作用

iphone - iPhone 上完全奇怪的字体渲染

java - 代码错误(java.awt.image.RasterFormatException)

Applet 中显示 Java Awt 组件但不显示 Swing 组件

java - 如何给这个按钮添加 Action 监听器?

java - 向 COM 端口发送字符串

java - 需要有关包含 100 多个字段的领域对象建模的帮助

java - 计算 StdIn 中的行数和字符数

javascript - 更改数组中特定元素的字体颜色 - Javascript

c# - 我如何从 C# 打印点阵字体的文本?