[en] How to word wrap text in Graphics2D.drawString in Java

Google wasn’t awfully helpful while I was searching for solution to word wrapping a text when drawing in Java, so let’s teach Google this: 😉

    private void drawStringRect(Graphics2D graphics, int x1, int y1, int x2, int y2, 
        float interline, String txt) {
        AttributedString as = new AttributedString(txt);
        as.addAttribute(TextAttribute.FOREGROUND, graphics.getPaint());
        as.addAttribute(TextAttribute.FONT, graphics.getFont());
        AttributedCharacterIterator aci = as.getIterator();
        FontRenderContext frc = new FontRenderContext(null, true, false);
        LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
        float width = x2 - x1;

        while (lbm.getPosition() < txt.length()) {
            TextLayout tl = lbm.nextLayout(width);
            y1 += tl.getAscent();
            tl.draw(graphics, x1, y1);
            y1 += tl.getDescent() + tl.getLeading() + (interline - 1.0f) * tl.getAscent();
            if (y1 > y2) {
                break;
            }
        }
    }