Search code examples
javaswinggraphicstextmeasurement

How do we do text measurements without a prior call to paintComponent?


Hi all I need to do some text measuring using java.awt.font.FontRenderContext, however this class requires me to supply a graphics object.

From what I know, the only way I could grab a graphics object is through the paintComponent / paint methods:

@Override public void paintComponent(java.awt.Graphics g){ //...

However I need to do this measurement even before the paintComponent method is called. I was wondering what's the best solution to this problem?

Do I create a dummy JLabel to do the job?


Solution

  • No need to create dummy GUI components. You could for instance create a BufferedImage

    Graphics g = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB).getGraphics();