I'm trying to display text inside a rectangle which I have the dimensions of (x, y, width, and height). However, if the text's length is long enough to the point where the text would leak outside the rectangle, I want to instead display as many characters as possible in a single line, followed by ellipses (...). I am aware that I can use the Graphics.getFontMetrics().stringWidth(text) to get the width the text would occupy in pixels. I could use this method by looping through, adding a character at a time to the string that would be displayed and checking if its width exceeds the rectangle's width. However, this feels inefficient.
As such, I want to know if there is a better/efficient way of doing this.