Search code examples
javaswinggraphics2ddrawstring

Java Swing Graphics2D drawString slow initiation?


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?


Solution

  • 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.