Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 288
Pacerier Avatar asked Dec 13 '22 07:12

Pacerier


2 Answers

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();
like image 194
aioobe Avatar answered Jan 17 '23 02:01

aioobe


However I need to do this measurement even before the paintComponent method is called

You should probably be overriding the getPreferredSize() method of the component. This is how Swing components know how to size and layout components before they are visible.

A JLabel uses the following:

FontMetrics fm = getFontMetrics(getFont());

Or if you need the FontRenderContext() then you can probably use the getGraphics() method of the object. Normally I recommend not to use this method, but that is because people then try to do custom painting with the Graphics object. However in this case you just want the Graphics object to measure the text so it should be ok.

like image 26
camickr Avatar answered Jan 17 '23 01:01

camickr