3

I have encountered a very strange behavior of Java Graphics2D draw String.

If I set a font name, such as

Font f = new Font("Helvetica", Font.PLAIN, 10);

Then on the screen device the first call to g2D.drawString can take as much as 600ms. This creates a screen jam, it's not significant but quite annoying.

Switching the font name to defaults such as "Monospaced" will solve the problem.

Anyone has encountered similar issues?

Gang Su
  • 1,187
  • 10
  • 12

1 Answers1

3

That happens because you are loading the Font inside the paint method (when you paint the string first time), which is a bad thing to do. You should either set component's font if it is the only font you are using or atleast load it before painting the component.

Mikle Garin
  • 10,083
  • 37
  • 59
  • Hi @mgarin no I made sure that the Font was not loaded within the paint method. I loaded the font in the constructor, and it took ridiculously long time for the first draw. Another weird thing is if I create a buffered image, the bufferedImage.createGraphics() can take 500 - 600ms to finish too. I don't know whether it's because of the iMac I am using - I am running Windows 7 on a iMac 27. Thank you for your answer! – Gang Su May 02 '12 at 15:02
  • 2
    How exactly do you load Font before the paint method call? Simply adding a line like "Font font = new Font(...);" will not initialize that Font - it will just create a Font object to manipulate actual font that will be loaded on first real paint call. I guess bufferedImage.createGraphics() can take a while if you are creating some large image (for e.g. 5000x5000) but i am not sure - better provide some code with that problem in a separate question... – Mikle Garin May 02 '12 at 15:27
  • @MikleGarin Did you figure out how to load the font? I can't seem to figure it out. – Indiana Kernick Mar 02 '19 at 05:10
  • @Kerndog73 not really, but it (probably) shouldn't be too hard to figure out - just need to debug the `Font` class and see what exactly gets initialized upon actual `Font` usage and then look for options `Font` class provides to initialize that and forcefully do that when you need to. – Mikle Garin Mar 02 '19 at 10:01