Java 中如何在没有图形的情况下获取文本前进 (stringWidth)?

How to get text advance (stringWidth) without a Graphics in Java?

如何在 Java 中没有 Graphics 实例的情况下获取文本前进 (stringWidth)?

doc examples中,stringWidth()取自FontMetrics,而FontMetrics取自Graphics

是否可以在没有Graphics的情况下获得相同的东西?

在下面的注释中说,Graphics 是必需的,因为它包含 FontRenderContext。但是我有FontRenderContext,就是没有Graphics

所以,假设我有 FontRenderContext 而没有 Graphics。那我怎么得到stringWidth()呢?

而“A FontRenderContext which is directly constructed will most likely not represent any actual graphics device, and may lead to unexpected or incorrect results," you can obtain useful metrics from an instance of TextLayout, as shown here and here

FontRenderContext frc = new FontRenderContext(null, false, false);
TextLayout layout = new TextLayout(text, font, frc);
System.out.println(layout.getBounds());