在第二屏里显示打开的ANSI文本文件的内容。在源代码所在目录里先建一个1.txt文本文件,随便写几个字。当然,如果你要在手机上运行Jar,Jar所在目录里也要有这个文本文件。代码我也不解释了,其实局部代码都容易看明白。这循序渐进学J2Me到这就先告一段落了,万事开头难,这已经开了头,后面就上网找代码慢慢拼凑,慢慢debug吧,NetBeans自带的样例写得很好,好好研究。
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
* @author netscaner
*/
public class Midlet extends MIDlet implements CommandListener {
private Form showForm;
private StringItem stringItem;
private Command exitCommand;
private Command NextCommand;
private Form NextScreen;
/*
打开ANSI文本文件,载入文本。这段代码是抄来的,别人博客上的
http://hi.baidu.com/wishwingliao/blog/item/220993dd184dab345982dd50.html
J2ME读取本地文本文件(ANSI,Unicode,Unicode big endian,UTF-8编码)_为你心醉
*/
private String loadText(String yourfilename)
{
InputStream is = null;
String strs = "";
try
{
is =getClass().getResourceAsStream(yourfilename);
InputStreamReader isr = new InputStreamReader(is);
StringBuffer buffer = new StringBuffer();
int ch;
while ((ch = isr.read()) > -1)
{
buffer.append((char)ch);
}
strs = buffer.toString();
if (isr != null) isr.close();
if(buffer != null) buffer = null;
}
catch(IOException e)
{
}
return strs;
}
public StringItem getStringItem() {
if (stringItem == null) {
stringItem = new StringItem("Hello", "Hello, World!");
}
return stringItem;
}
public Form getForm() {
if (showForm == null) {
showForm = new Form("Welcome", new Item[] { getStringItem() });
showForm.addCommand(getExitCommand());
showForm.addCommand(getNextCommand());
showForm.setCommandListener(this);
}
return showForm;
}
public void startMIDlet() {
switchDisplayable(null, getForm());
}
public void exitMIDlet() {
switchDisplayable (null, null);
destroyApp(true);
notifyDestroyed();
}
public void switchDisplayable(Alert alert, Displayable nextDisplayable) {
Display display = getDisplay();
if (alert == null) {
display.setCurrent(nextDisplayable);
} else {
display.setCurrent(alert, nextDisplayable);
}
}
public Display getDisplay () {
return Display.getDisplay(this);
}
public Command getExitCommand() {
if (exitCommand == null) {
exitCommand = new Command("Exit", Command.EXIT, 0);
}
return exitCommand;
}
public Command getNextCommand() {
if (NextCommand == null) {
NextCommand = new Command("Next", Command.SCREEN, 1);
}
return NextCommand;
}
public void commandAction(Command command, Displayable displayable) {
if (command == exitCommand) {
exitMIDlet();
}
if (command == NextCommand) {
Form NextScreen = new Form("Next",null);
NextScreen.append(new StringItem("Next", "Next Screen"));
String str="";
str = loadText("/1.txt");
NextScreen.append(str);
NextScreen.addCommand(getExitCommand());
NextScreen.setCommandListener(this);
Display display = getDisplay();
display.setCurrent(NextScreen);
}
}
public void startApp() throws MIDletStateChangeException {
startMIDlet ();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}