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?
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With