1

I have an issue where I need to test the character at the stringwidth of 256. However, when I do a charAt(index) test, I get an indexoutofbounds exception because 256 (buffered image width) is actually longer than the string.length. My question is once I hit the stringwidth of 256, how do i test the character at that width?

Mike
  • 11
  • 1

2 Answers2

1

Java, as with all "C like" languages, uses zero-based indexing, ie the first element of an array (or collection etc) has index 0, the second has index 1, etc

To access the 256th char, use charAt(255).

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Thanks for your reply but that's not really my issue. The string I'm testing is only 160 characters long. However, the fontmetrics stringWidth is 650. I need to wrap the string in increments of 256 at the space char. I don't know who to translate the strinwidth to the string length in order to use the charAt. – Mike Dec 29 '15 at 17:28
  • @Mike What exactly are you trying to do? Is it just "to wrap the string in increments of 256 at the space char"? If so, what do you mean "at the space char"? Does that mean "split a string at spaces such that each part is as large as possible without exceeding 256 chars"? Please clarify – Bohemian Dec 30 '15 at 01:04
0

You would need to use the charWidth() method for all characters in your string to know which character occurs at width 256.

"I need to wrap the string in increments of 256 at the space char" - what does it mean? You could always render it to an offscreen buffer and use drawImage() to render it in 256 pixels wide chunks.

mattiash
  • 172
  • 7
  • I have a bufferedimage with a width of 256. I'm overlaying text onto that image. I need to accommodate for strings that exceed the width of the bufferedimage. Therefore, I would like to iterate over the string wrapping it at each maxwidth of the image. i.e. 256 – Mike Dec 29 '15 at 20:04