請考慮下面的代碼將被用於計算寬度像素爲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'是術語。 –
謝謝,不知道。 (btw:Oracle稱它爲_static初始化塊)。 我更新了答案。 – Felix
@Felix ..是的。他們都會這樣做。 :) –