Text wrapping in Java ME
Article Metadata
The following code illustrates how to wrap text.
import java.util.Enumeration;
import java.util.NoSuchElementException;
import javax.microedition.lcdui.*;
//www.astrientlabs.com
public class LineEnumeration implements Enumeration {
private Font font;
private String text;
private int width;
private int position;
private int length;
private int start = 0;
public LineEnumeration(Font font, String text, int width) {
this.font = font;
this.text = text;
this.width = width;
this.length = text.length();
}
public boolean hasMoreElements() {
return (position < (length-1));
}
public Object nextElement() throws NoSuchElementException {
try {
return text.substring(start,(start = next()));
} catch ( IndexOutOfBoundsException e ) {
throw new NoSuchElementException(e.getMessage());
} catch ( Exception e ) {
throw new NoSuchElementException(e.getMessage());
}
}
private int next() {
int i = position;
int lastBreak = -1;
for ( ;i < length && font.stringWidth(text.substring(position,i)) <= width; i++ ) {
if ( text.charAt(i) == ' ' ) {
lastBreak = i;
} else if ( text.charAt(i) == '\n' ) {
lastBreak = i;
break;
}
}
if ( i == length ) {
position = i;
} else if ( lastBreak <= position ) {
position = i;
} else {
position = lastBreak;
}
return position;
}
}


18 Sep
2009
Sometimes it becomes crucial for developers to do something that is not available ready made. Text Wrapping is just a requirement in many applications when we want to display data that may be fetched from internet and we want it to be displayed in good manner so that we can increase user experience and they no longer need to scroll horizontally to read the full text.
This article shows a complete implementation through which developers can cope up with text wrapping problem. Code has is perfectly running so any one can try now. Given code becomes so handy when we are developing apps for different screen sizes. So in that case the longer text will be automatically wrapped according to the phone's screen size. This article helps me lot in my under going Share Tips application where i am displaying text on the screen from one text file.