2012-11-14 83 views
2

請考慮下面的代碼將被用於計算寬度像素爲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 
     } 
} 

如果我宣佈fontmetricsstatic類型,編譯器不會讓我做這件事。爲什麼這樣 ?如何初始化fontmetrics一次並計算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); 
    } 

回答

5

編譯器確實允許你這樣做。但是,它不會讓您訪問您在方法中聲明的變量,因爲它們的可見性僅限於該靜態塊。

你應該聲明爲靜態變量是這樣的:

private static final Font FONT = new Font(...); 
1

你必須使fontmetrics領域靜:

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 
     } 
} 
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 
    } 
} 
+2

'靜態初始化block'是術語。 –

+0

謝謝,不知道。 (btw:Oracle稱它爲_static初始化塊)。 我更新了答案。 – Felix

+0

@Felix ..是的。他們都會這樣做。 :) –

1

塊中的聲明僅具有該塊的名稱範圍。即使它是全球性的,您也無法訪問它。

相關問題