0

The program I'm making uses string related calculations done with FontMetrics. As FontRenderContext may vary, it is required to make the calculations correctly and I have a static instance of it saved so I can access it anywhere.

I found a way to calculate string width using font and context (without Graphics2D instance):

font.getStringBounds(string, Window.fontRenderContext).getWidth()

The problem I have is calculating descent, ascent and anything else FontMetrics provides. I could:

  • Create a canvas, get its Graphics, apply all of the settings to it and get FontMetrics. It would require a lot of code and it would not work stably as Canvas.getGraphics can arbitrarily return null.
  • Delay those calculations until my paint(Graphics2D g) method is run, where I could get FontMetrics directly.
  • Try to get needed values from Font.getStringBounds. I would doubtfully manage to do it.

It confuses me that I can get getStringBounds just from font and context (getStringBounds consists of FontMetrics values), but it turns into such headache when I need to get original descent, ascent, etc values.

  • Have you tried `SwingUtilities.computeStringWidth()`? – WJS Mar 09 '20 at 02:09
  • @WJS This method requires FontMetrics and SwingUtilities has no such method ascent and descent. As I said I found a way to find width but I can't find anything else. (I can't calculate where to put the text on Y axis) – supernovaw Mar 09 '20 at 02:36
  • [This SO Post](https://stackoverflow.com/a/27631737/4725875) might help out. – DevilsHnd Mar 09 '20 at 03:02
  • Unfortunately no, I already know how FontMetrics work. – supernovaw Mar 09 '20 at 14:57

0 Answers0