As shown in the following picture, an AttributedString is drawn on a JPanel (500X500).
The FontMetrics.getStringBounds() of that AttributedString gives a
The FontMetrics only receives a CharacterIterator, and does not take into account that it is actually an AttributedCharacterIterator. You can use a TextMeasurer to compute the actual bounds of your string. For comparison, add this after you called the drawString method:
// Compensate for the 50,50 of the drawString position
g.translate(50, 50);
g.setColor(Color.RED);
Rectangle2D wrongBounds = fm.getStringBounds(
text.getIterator(), 0, text.getIterator().getEndIndex(), g);
g.draw(wrongBounds);
System.out.println("wrong: "+wrongBounds);
g.setColor(Color.BLUE);
AttributedCharacterIterator iterator = text.getIterator();
TextMeasurer tm = new TextMeasurer(iterator, g.getFontRenderContext());
Rectangle2D rightBounds = tm.getLayout(0, iterator.getEndIndex()).getBounds();
g.draw(rightBounds);
System.out.println("right: "+rightBounds);
(And BTW: Don't call g.dispose() on the Graphics that was handed to you in the paintComponent method)