Question

enter image description here

The string in the picture is over 570 pixels (I know this because I used FontMetrics to get it), though I checked the java documentation, String doesn't appear to have a method that lets you splice a string if it's over x pixels.

Was it helpful?

Solution

Keep cutting the last character from the string until it fits.

String initialString = "1234567890";
String firstPart = initialString;
while (metrics.stringWidth(firstPart) > MAX_WIDTH) {
    firstPart = firstPart.substring(0, firstPart.length() - 1);
}
String secondPart = initialString.substring(firstPart.length(), initialString.length());

OTHER TIPS

Strings are objects in Java and do not have any representation of how they are processed in terms of pixels on screen. There is no way to use the String object itself to do what it is you want to do (unless you implement your own methods).

You need to check your method for "printing" your String to screen, and modifying that method so that the string does not get over 570 px long.

Let's say you have a method that prints text:

text(myText, width, height);

Here you would set the width to 570.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top