String length in pixels in Java

后端 未结 3 1208
抹茶落季
抹茶落季 2021-01-11 10:32

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?

3条回答
  •  抹茶落季
    2021-01-11 11:21

    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.

提交回复
热议问题