请考虑以下代码,用于计算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)
如果我声明font和metrics是类型static,编译器将不允许我这样做.为什么这样 ?如何初始化font和metrics一次并计算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)
编译器确实允许你这样做.但是,它不允许您从方法访问您在那里声明的变量,因为它们的可见性仅限于该静态块.
您应该将它们声明为静态变量,如下所示:
private static final Font FONT = new Font(...);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
148 次 |
| 最近记录: |