Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Text wrapping in Java ME

From Wiki
Jump to: navigation, search
Article Metadata
Article
Created: sparkystar (20 Dec 2007)
Last edited: lpvalente (13 Oct 2013)

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;
}
}

Usage Example

    LineEnumeration e = new LineEnumeration(myFont,myText,lineWidth);
while ( e.hasMoreElements() ) {
g.drawString(e.nextElement().toString(), startX,startY, Graphics.TOP | Graphics.LEFT);
startY += myFont.getHeight();
}
This page was last modified on 13 October 2013, at 16:31.
68 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×