为什么静态块中不允许静态字段声明?

Gee*_*eek 2 java swing awt

请考虑以下代码,用于计算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 
      }
}
Run Code Online (Sandbox Code Playgroud)

如果我声明fontmetrics是类型static,编译器将不允许我这样做.为什么这样 ?如何初始化fontmetrics一次并计算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);
  }
Run Code Online (Sandbox Code Playgroud)

Dan*_* D. 5

编译器确实允许你这样做.但是,它不允许您从方法访问您在那里声明的变量,因为它们的可见性仅限于该静态块.

您应该将它们声明为静态变量,如下所示:

private static final Font FONT = new Font(...);
Run Code Online (Sandbox Code Playgroud)