请考虑以下代码,该代码将用于计算 a 的像素宽度String
:
public class ComponentUtils {
static {
Font font = new Font("Verdana", Font.BOLD, 10);
FontMetrics metrics = new FontMetrics(font) {
};
}
public static String calculateWidthInPixels(String value) {
//Using the font metrics class calculate the width in pixels
}
}
如果我将font
and声明metrics
为 type static
,编译器不会让我这样做。为什么这样 ?如何初始化font
andmetrics
一次并计算内部calculateWidthInPixels
方法的宽度?
PS:以下主类始终按预期工作,并以像素为单位给出宽度。
public class Main {
public static void main(String[] args) {
Font font = new Font("Verdana", Font.BOLD, 10);
FontMetrics metrics = new FontMetrics(font){
};
Rectangle2D bounds = metrics.getStringBounds("some String", null);
int widthInPixels = (int) bounds.getWidth();
System.out.println("widthInPixels = " + widthInPixels);
}