×
Namespaces

Variants
Actions

TextWrapUtil to draw Multiple line text in Java ME

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

Contents

Overview

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;
break;
}
else
{
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)
break;
}
}
String line = text.substring(current, lineBreak + 1);
result.addElement(line);
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.
117 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.

×