2

The normal syntax for java.awt.Graphics.drawString() includes defining the X and Y coordinates for the string. I want to draw a string that has a width and height attribute for text wrapping. Is there a way to specify a java.awt.Rectangle for the string you are trying to draw? Would I have to write something to decide where the word wrap should cut it off or is their an easier way? Thanks!

2 Answers 2

2

This is actually a little bit complicated and somewhat convoluated, but essentially, you need to make use of the LineBreakMeasurer class to help you break the text down into manageable chunks based on the available width

See Drawing Multiple Lines of Text for more details and an example

Sign up to request clarification or add additional context in comments.

Comments

1

I don't think there's a built in way to do that, but you can implement your own wrapping if you get the width of the string with something like below:

FontMetrics fontMetrics = new FontMetrics(Graphics.getFont());
int width = fontMetrics.stringWidth("Potentially needs wrapping");

Then split the message into multiple strings as necessary.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.