Home » Java » Is it possible to get the right string size without use paintComponent(Graphics g)?

Is it possible to get the right string size without use paintComponent(Graphics g)?

Posted by: admin May 17, 2018 Leave a comment

Questions:

Actually I have these methods to get the width/height size of a string, both requires the command inside a paint component. But I want to get this values inside a class constructor. This is possible?

public int getStringWidth(Graphics g){
    g2d = (Graphics2D) g;
    metrics = g2d.getFontMetrics(this.font);
    return metrics.stringWidth(this.string);
}

public int getStringHeight(Graphics g){
    g2d = (Graphics2D) g;
    metrics = g2d.getFontMetrics(this.font);
    int height = (int)font.createGlyphVector(metrics.getFontRenderContext(), this.string).getVisualBounds().getHeight();    
    return height;
}

font.createGlyphVector(metrics.getFontRenderContext(), this.string).getVisualBounds().getHeight() it’s the best command that I got to precisely calculate the string height size and it needs Graphics g too.

Answers: