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. Thanks for all your past and future contributions.

TextWrapUtil to draw Multiple line text in Java ME

From Wiki
Jump to: navigation, search
Article Metadata
Created: senthilkumar05 (28 Aug 2009)
Last edited: hamishwillee (16 Dec 2013)



This code snippet below demonstrates how to break a long text in multiple lines and draw them on the Canvas.

Header file

Microedition.lcdui.* and java.util.* are needed for this code snippet.

import javax.microedition.lcdui.*;
import java.util.*;

Source Code

Wrap Method

It divides the long text file into separate lines based on the provided font and width of the area in which it to be rendered and return it as a

vector of multiple lines.

static Vector wrap (String text,Font font, int width) 
Vector result = new Vector ();
if (text ==null)
return result;
boolean hasMore = true;
// The current index of the cursor
int current = 0;
// The next line break index
int lineBreak = -1;
// The space after line break
int nextSpace = -1;
while (hasMore)
//Find the line break
while (true)
lineBreak = nextSpace;
if (lineBreak == text.length() - 1)
// We have reached the last line
hasMore = false;
nextSpace = text.indexOf(' ', lineBreak+1);
if (nextSpace == -1)
nextSpace = text.length() -1;
int linewidth = font.substringWidth(text,current, nextSpace-current);
// If too long, break out of the find loop
if (linewidth > width)
String line = text.substring(current, lineBreak + 1);
current = lineBreak + 1;
return result;

drawMultilineString Method

It draws the given long text String str, dividing it into multiple lines using the above wrap method and draws it on the screen using

g.drawString method in the given font and returns the next line y value.

static public int drawMultilineString (Graphics g,Font font, String str, int x, int y,int anchor, int width) 
g.setFont (font);
Vector lines = wrap(str, font, width);
for (int i = 0; i<lines.size(); i++)
int liney = y + (i * font.getHeight());
g.drawString((String)lines.elementAt(i), x,liney, anchor);
return y + (lines.size() * font.getHeight());
This page was last modified on 16 December 2013, at 06:55.
82 page views in the last 30 days.