문제

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.

도움이 되었습니까?

해결책

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());

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top