Q:

Font dimensions in different object to JPanel

I'm not sure how to ask this, I have a subclass JPanel that draws strings with paintComponent. And I have a class that takes String string, int xPos, int yPos, Font font as arguments, the object is then drawn with g.drawString(text.getstring, etc...).
However, the problem is that when the text class is constructed I would like to calculate the width and height of the text based on the string and font given, but the way to do that seems to be by doing this:
FontMetrics = g.getFontMetrics(Font);
int height = metrics.getHeight();
int width = metrics.stringWidth(string);

the problem is that g has to be the 'Graphics' object from paintComponent, however that doesn't exist in the scope of the class, should I pass it as a parameter to the text class? Or is there a more elegant way of doing this?

A:

You can't compute the width of a string without the graphics context you are going to use to draw it. See this question.
So you need will need to calculate the string width within your paintComponent method, every time it is called.
However, for an approximation, I use the font size as the height and a fudge factor for the width: string.length() * fontSize * 0.545f (where we are working in floats with a scale factor of 100).

