I need to draw text with Graphics#drawString
I'm drawing on top of a JPanel
that changes both in width and height (by dragging).
I'm looking for a solution to generate bounds, so that I can warp the lines automatically and adapt the text accordingly, without overflows.
I figured I could just hardcode it myself by getting the length in pixels with fontMetrics, however, I would rather have a component that does this automatically (drawString
also doesn't support '\n'
).
In the docs as well as in this other answer I found this:
Graphics2D g = ...;
Point2D loc = ...;
Font font = Font.getFont("Helvetica-bold-italic");
FontRenderContext frc = g.getFontRenderContext();
TextLayout layout = new TextLayout("This is a string", font, frc);
layout.draw(g, (float)loc.getX(), (float)loc.getY());
Rectangle2D bounds = layout.getBounds();
bounds.setRect(bounds.getX()+loc.getX(),
bounds.getY()+loc.getY(),
bounds.getWidth(),
bounds.getHeight());
g.draw(bounds);
Which does draw the string and the bounds, but they have no effect, so no luck here.
Any class I could use?