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);
}
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(...);
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With