JavaMe開發(fā)繪制可自動換行文本
【問題描述】
JavaMe Graphics類中的drawString不支持文本換行,這樣繪制比較長的字符串時(shí),文本被繪制在同一行,超過屏幕部分的字符串被截?cái)嗔?。如何使繪制的文本能自動換行呢?
【分析】
drawString無法實(shí)現(xiàn)自動換行,但可以實(shí)現(xiàn)文本繪制的定位。因此可考慮,將文本拆分為多個(gè)子串,再對子串進(jìn)行繪制。拆分的策略如下:
1 遇到換行符,進(jìn)行拆分;
2 當(dāng)字符串長度大于設(shè)定的長度(一般為屏幕的寬度),進(jìn)行拆分。
【步驟】
1 定義一個(gè)String和String []對象;
private String info; private String info_wrap[];
2 實(shí)現(xiàn)字符串自動換行拆分函數(shù)
StringDealMethod.java
package com.token.util;
import java.util.Vector;
import javax.microedition.lcdui.Font;
public class StringDealMethod {
public StringDealMethod()
{
}
// 字符串切割,實(shí)現(xiàn)字符串自動換行
public static String[] format(String text, int maxWidth, Font ft) {
String[] result = null;
Vector tempR = new Vector();
int lines = 0;
int len = text.length();
int index0 = 0;
int index1 = 0;
boolean wrap;
while (true) {
int widthes = 0;
wrap = false;
for (index0 = index1; index1 < len; index1++) {
if (text.charAt(index1) == '\n') {
index1++;
wrap = true;
break;
}
widthes = ft.charWidth(text.charAt(index1)) + widthes;
if (widthes > maxWidth) {
break;
}
}
lines++;
if (wrap) {
tempR.addElement(text.substring(index0, index1 - 1));
} else {
tempR.addElement(text.substring(index0, index1));
}
if (index1 >= len) {
break;
}
}
result = new String[lines];
tempR.copyInto(result);
return result;
}
public static String[] split(String original, String separator) {
Vector nodes = new Vector();
//System.out.println("split start...................");
//Parse nodes into vector
int index = original.indexOf(separator);
while(index>=0) {
nodes.addElement( original.substring(0, index) );
original = original.substring(index+separator.length());
index = original.indexOf(separator);
}
// Get the last node
nodes.addElement( original );
// Create splitted string array
String[] result = new String[ nodes.size() ];
if( nodes.size()>0 ) {
for(int loop=0; loop<nodes.size(); loop++)
{
result[loop] = (String)nodes.elementAt(loop);
//System.out.println(result[loop]);
}
}
return result;
}
}
3 調(diào)用拆分函數(shù),實(shí)現(xiàn)字符串的拆分
int width = getWidth();
Font ft = Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_BOLD,Font.SIZE_LARGE);
info = "歡迎使用!\n"
+"1 MVC測試;\n"
+"2 自動換行測試,繪制可自動識別換行的字符串。\n";
info_wrap = StringDealMethod.format(info, width-10, ft);
4 繪制字符串
int width = getWidth();
Font ft = Font.getFont(Font.FACE_PROPORTIONAL,Font.STYLE_BOLD,Font.SIZE_LARGE);
info = "歡迎使用!\n"
+"1 MVC測試;\n"
+"2 自動換行測試,繪制可自動識別換行的字符串。\n";
info_wrap = StringDealMethod.format(info, width-10, ft);
繪制的效果如圖1所示:

相關(guān)文章
Java實(shí)現(xiàn)冒泡排序與雙向冒泡排序算法的代碼示例
解決Eclipse配置Tomcat出現(xiàn)Cannot create a server using the selected
spring-shiro權(quán)限控制realm實(shí)戰(zhàn)教程
Java遞歸基礎(chǔ)與遞歸的宏觀語意實(shí)例分析
java使用EasyExcel實(shí)現(xiàn)Sheet的復(fù)制與填充

