Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a static field declaration not allowed in a static block?

Tags:

java

swing

awt

Please consider the following code which will be used to calculate the width in pixel for 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 
      }
}

If I declare the font and metrics to be of type static , the compiler won't let me do this . Why so ? How do I initialize the font and metrics once and calculate the width inside calculateWidthInPixels method ?

P.S: The following main class always works as expected and gives the width in pixels .

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);
  }
like image 204
Geek Avatar asked Dec 09 '25 13:12

Geek


2 Answers

The compiler does actually allow you to do that. However, it won't let you access the variables you declared there from your method because their visibility is restricted to that static block.

You should declare them as static variables like this:

private static final Font FONT = new Font(...);
like image 130
Dan D. Avatar answered Dec 12 '25 01:12

Dan D.


You have to declare the fields in the class scope and not in the static initialization block:

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 
    }
}
like image 32
Felix Avatar answered Dec 12 '25 01:12

Felix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!