Join Now
Quality Rating:
  • Currently 0.0 / 5
(0.0 / 5 - 0 votes cast)
Expertise Level:
  • Currently 0.0 / 5
(0.0 / 5 - 0 votes cast)

This page was last modified 01:59, 4 July 2008.

Text wrapping in J2ME

From Forum Nokia Wiki

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();
    }
Related Discussions
Thread Thread Starter Forum Replies Last Post
low-level sockets shadow-2005 Symbian Networking & Messaging 12 2006-07-12 13:46
how to create a scrollable but non-editable edwin? s3ni General Symbian C++ 16 2003-12-29 09:52
How to use T9 language dictionary directly? mike.b Symbian User Interface 4 2004-10-06 10:45
Structures in Symbian deepchand86 General Symbian C++ 9 2008-08-27 08:43
midp development without forte/jbuilder joostdiepenmaat Mobile Java Tools & SDKs 2 2002-08-29 11:44
 
Powered by MediaWiki
     
     RDF Facets:
     
     
     qfnZtopicQUqfnTopicZjavaQ
     qfnZtypeQUqfnTypeZCommunityContentQ
     qfnZtypeQUqfnTypeZWebpageQ
     qfnZtypeQUqfnTypeZWikiContentQ
     qmarsZlanguageQUxhttpE3aE2fE2fswE2enokiaE2ecomE2flanguageE2d1E2fenX