2

请考虑以下代码,该代码将用于计算 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 
      }
}

如果我将fontand声明metrics为 type static,编译器不会让我这样做。为什么这样 ?如何初始化fontandmetrics一次并计算内部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);
  }
4

4 回答 4

5

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

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

private static final Font FONT = new Font(...);
于 2012-11-14T12:23:05.133 回答
4

您必须在类范围内声明字段,而不是在静态初始化块中:

public class ComponentUtils {
    private static Font FONT;
    private static FontMetrics METRICS;

    static {
        FONT= new Font("Verdana", Font.BOLD, 10);
        METRICS= new FontMetrics(font) {};
    }

    public static String calculateWidthInPixels(String value) {
       //Using the font metrics class calculate the width in pixels 
    }
}
于 2012-11-14T12:22:38.530 回答
1

您必须将fontandmetrics字段设为静态:

 public class ComponentUtils {
      static Font font;
      static FontMetrics metrics;

      static {
         font = new Font("Verdana", Font.BOLD, 10);
         metrics = new FontMetrics(font) {
        };
      }

    public static String calculateWidthInPixels(String value) {
       //Using the font metrics class calculate the width in pixels 
      }
}
于 2012-11-14T12:20:41.950 回答
1

块中的声明仅具有该块的名称范围。即使它是全球性的,您也无法访问它。

于 2012-11-14T12:23:02.413 回答