请考虑以下代码,该代码将用于计算 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
和metrics
声明为static
类型,编译器将不允许我这样做。为什么这样 ?如何初始化 font
和 metrics
一次并在 calculateWidthInPixels
方法中计算宽度?
P.S:下面的主类总是按预期工作,并给出以像素为单位的宽度。
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);
}
最佳答案
编译器实际上允许您这样做。但是,它不会让您从您的方法访问您在此处声明的变量,因为它们的可见性仅限于该静态 block 。
您应该像这样将它们声明为静态变量:
private static final Font FONT = new Font(...);
关于java - 为什么静态 block 中不允许静态字段声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13378710/