Really slow obtaining font metrics.
Posted
by Artur
on Stack Overflow
See other posts from Stack Overflow
or by Artur
Published on 2010-03-16T13:48:07Z
Indexed on
2010/03/21
0:21 UTC
Read the original article
Hit count: 790
So the problem I have is that I start my application by displaying a simple menu. To size and align the text correctly I need to obtain font metrics and I cannot find a way to do it quickly. I tested my program and it looks like whatever method I use to obtain font metrics the first call takes over 500 milliseconds!? Because of it the time it takes to start-up my application is much longer than necessary.
I don't know if it is platform specific or not, but just in case, I'm using Mac OS 10.6.2 on MacBook Pro (hardware isn't an issue here).
If you know a way of obtaining font metrics quicker please help.
I tried these 3 methods for obtaining the font metrics and the first call is always very slow, no matter which method I choose.
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import javax.swing.JFrame;
public class FontMetricsTest extends JFrame {
public FontMetricsTest() {
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Font font = new Font("Dialog", Font.BOLD, 10);
long start = System.currentTimeMillis();
FontMetrics fontMetrics = g2.getFontMetrics(font);
// LineMetrics fontMetrics1 =
// font.getLineMetrics("X", new FontRenderContext(null, false, false));
// FontMetrics fontMetrics2 = g.getFontMetrics();
long end = System.currentTimeMillis();
System.out.println(end - start);
g2.setFont(font);
}
public static void main(String[] args) {
new FontMetricsTest();
}
}
© Stack Overflow or respective owner