gpt4 book ai didi

java - 获取 FontMetrics StackOverflowError

转载 作者:搜寻专家 更新时间:2023-11-01 02:26:22 25 4
gpt4 key购买 nike

运行以下代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com