How do we perform text measurements without first calling paintComponent?

Hello everyone I need to take some text measurements using java.awt.font.FontRenderContext , however this class requires me to supply a graphic object.

From what I know, the only way to capture a graphic is with the paintComponent / paint methods:

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

However, I need to take this measurement before calling the paintComponent method. I was wondering what is the best solution to this problem?

Am I creating a dummy JLabel to do the job?

+4
source share
5 answers

No need to create dummy GUI components. For example, you can create a BufferedImage

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

However, I need to take this measurement before the paintComponent method is called

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

A JLabel uses the following:

 FontMetrics fm = getFontMetrics(getFont()); 

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

+4
source

TextLayout may be useful in this context. This example compares the result with the result obtained from the text component FontMetrics , and this example extends to @aioobe BufferedImage .

+3
source

Or you can do it in your component constructor

 Font font = Font.createFont(Font.TRUETYPE_FONT, new File("ARIAL.TTF")); font = font.deriveFont(12f); FontMetrics fontMetrics = getFontMetrics(font); 
+2
source

Following a response from aioobe is a smart way to get graphics. Perhaps everyone understands this, but the Graphics object comes with a specific font, which, using aioobe, can be any general way to get graphics.

I had to do this (Jython):

 g = java.awt.image.BufferedImage(1, 1, java.awt.image.BufferedImage.TYPE_INT_RGB).graphics g.font = my_table.font 

After that, it gives an exact figure before something is realized ... cheers:

 hw_width = g.fontMetrics.stringWidth( "Hello World" ) 
0
source

Source: https://habr.com/ru/post/1383034/


All Articles