关于一大段英语单词字符输出按指定屏幕长度和换行输出在屏幕上的方法,且换行时如果是一个单词没有展示完,会在最后处加上“—”字符。在第二行继续展示的方法。

来源:互联网 发布:粤语歌 其他方言 知乎 编辑:程序博客网 时间:2024/05/04 06:51

1。定义一个字符,来放你要输出的文字

String strAbout="My father was a self-taught mandolin player. He\n"+" was one of the best string instrument players in\n"+" our town. He could not read music";

2.再定义一个字符数组,把你要输出的文字整合到该数组。

   public String strAboutSZ[];

   strAboutSZ = Test1(strAbout, WIDTH - 55(这是输出在屏幕在一行的宽度), smallFont(字的大小), '\n'(主动换行标识符));

这是Test1方法,

 String lst_string[];// 列表字符串
int list_scrolly = 26;
int fontHeight = smallFont.getHeight() + 1;

public static String[]  Test1(String text, int width, Font font,
char newLine) {
Vector vector = new Vector();
int offset = 0;
int maxLength = text.length(); // 字符串总长度
boolean endFlag; // 标记是否已经换行
 
while (offset < maxLength) {
if (text.charAt(offset) == newLine) {
// 如果第一个字符是换行符,添加一个空串,偏移值加一,继续检索
vector.addElement("");
offset++;
} else {
endFlag = false;
for (int i = 1; offset + i < maxLength; i++) {
if (text.charAt(offset + i) == newLine) {
// 遇到换行符,添加子串
int diff = offset + i;
if (newLine == '\n') {
diff += 1;
}
vector.addElement(text.substring(offset, diff));
offset += i + 1;
endFlag = true;
break;
} else if (font.charsWidth(text.toCharArray(), offset,
i + 1) > width) {
// 子串长度大于指定宽度,终止搜索,添加子串
if (i >= 2 && isLetter(text.charAt(offset + i))
&& isLetter(text.charAt(offset + i - 1))) {
// 判断结束相关的3个字符类型为字母,则添加换行连接符”-“
if (isLetter(text.charAt(offset + i - 2)))
vector.addElement(text.substring(offset, offset + i - 1) + "-");
else
vector.addElement(text.substring(offset, offset+ i - 1));
offset += (i - 1);
} else {
vector.addElement(text
.substring(offset, offset + i));
offset += i;
}
endFlag = true;
break;
}
}
if (!endFlag) {
// 搜索到整个原始串的结尾时,添加剩余的部分
vector.addElement(text.substring(offset));
break;
}
}
}
 
int size = vector.size();
String[] txt = new String[size];
for (int i = 0; i < size; i++)
txt[i] = ((String) vector.elementAt(i));
return txt;
}
// 字母ASCII码,A-Z:65-90,a-z:97-122
public static boolean isLetter(char c){
if((c >= 65 && c <= 90) || (c >= 97 && c <= 122))
return true;
return false;
}

 3,。输出字符串在屏幕上

    for (int i = 0; i < strAboutSZ.length; i++) {
g.drawString( strAboutSZ[i], 240, 20 + i
* (smallFont.getHeight()+10)(每行字的距离)
,17);

}                

原创粉丝点击