This is my linewrap code, it hasn’t failed me yet:
public ArrayList<String> splitLines(String s, FontMetrics fm) {
ArrayList<String> ret = new ArrayList<String>();
String ln = "";
StringTokenizer st = new StringTokenizer(s);
String nt;
while (st.hasMoreTokens()) {
nt = st.nextToken();
if (fm.stringWidth(ln + nt) >= maxWidth) {
ret.add(new String(ln));
ln = "";
ln += nt + " ";
} else {
ln += nt + " ";
}
}
ret.add(ln);
//fix the lengths
int lo = ret.size();
for (int i = 0; i < lo; i++) {
if (fm.stringWidth(ret.get(i)) > maxWidth) {
//umm
String the = ret.get(i);
String other = "";
int fk = 0;
for (int j = 0; j < the.length(); j++) {
char ch = the.charAt(the.length() - 1);
the = the.substring(0, the.length() - 1);
other += ch;
fk = j;
}
ret.set(i, the);
ret.add(i + 1, new StringBuffer(other).reverse().toString());
i--;
}
}
return ret;
}
Have fun and report bugs.