我为此非常努力。我需要将面板的大小调整为 AttributedString 的宽度。我的解决方案是:
double GetWidthOfAttributedString(Graphics2D graphics2D, AttributedString attributedString) {
AttributedCharacterIterator characterIterator = attributedString.getIterator();
FontRenderContext fontRenderContext = graphics2D.getFontRenderContext();
LineBreakMeasurer lbm = new LineBreakMeasurer(characterIterator, fontRenderContext);
TextLayout textLayout = lbm.nextLayout(Integer.MAX_VALUE);
return textLayout.getBounds().getWidth();
}
它使用LineBreakMeasurer为字符串查找 TextLayout,然后简单地检查 TextLayout 的与。(环绕宽度设置为 Integer.MAX_VALUE,因此比该宽度更宽的文本将被截断)。