13

Is there a way to calculate the length of a string in pixels, given a certain java.awt.Font object, that does not use any GUI components?

APerson
  • 8,140
  • 8
  • 35
  • 49
  • See also [this answer](http://stackoverflow.com/questions/6295084/cut-out-image-in-shape-of-text/6296381#6296381) for using a `GlyphVector`. It puts the final image in a GUI, but that is just to display it. – Andrew Thompson Nov 12 '12 at 14:54

4 Answers4

10

that does not use any GUI components?

It depends on what you mean here. I'm assuming you mean you want to do it without receiving a HeadlessException.

The best way is with a BufferedImage. AFAIK, this won't throw a HeadlessException:

Font font = ... ;
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
FontMetrics fm = img.getGraphics().getFontMetrics(font);
int width = fm.stringWidth("Your string");

Other than using something like this, I don't think you can. You need a graphics context in order to create a FontMetrics and give you font size information.

Brian
  • 17,079
  • 6
  • 43
  • 66
3

You can use the Graphics2D object to get the font bounds (including the width):

Graphics2D g2d = ...
Font font = ...
Rectangle2D f = font.getStringBounds("hello world!", g2d.getFontRenderContext());

But that depends on how you will get the Graphics2D object (for example from an Image).

dacwe
  • 43,066
  • 12
  • 116
  • 140
  • I assume that counts as a GUI component. – Link19 Nov 12 '12 at 14:48
  • @GlenLamb I differ, `Image`'s are not GUI components. – dacwe Nov 12 '12 at 14:49
  • I agree, but the specific need to do it WITHOUT GUI components would imply awt in general, otherwise the requirement makes little sense. – Link19 Nov 12 '12 at 14:53
  • @GlenLamb I don't understand what you are getting at. The `Graphics2D` might be obtained from something like `img.getGraphics()` (or rather `img.createGraphics()`) in Brian's code. – Andrew Thompson Nov 12 '12 at 14:56
  • @dacwe why would you specify "without GUI components" unless there was a need to avoid awt Graphics2d? Since that is pretty much how you would do it, even if you were using GUI. – Link19 Nov 12 '12 at 14:58
2

This gives the output of (137.0, 15.09375) for me. I have no idea what the units are, but it certainly looks proportionally correct and doesn't use Graphics2D directly.

    Font f = new Font("Ariel", Font.PLAIN, 12);
    Rectangle2D r = f.getStringBounds("Hello World! Hello World!", new FontRenderContext(null, RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT, RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT));
    System.out.println("(" + r.getWidth() + ", " + r.getHeight() + ")"); 
Link19
  • 586
  • 1
  • 18
  • 47
0

I needed to get length and width of a string before paintComponent was called so I could size the enclosing panel to the text dimensions. None of these techniques provided a sufficiently width and I did not have a Graphics object available. I resolved the issue by setting my font to "Monospaced".