在这之前我们做一个统一,把所有的代码默认编码方式都设置为UTF-8。
我们以一个简单的计算器为例来设计运行我们的第一个JavaME程序:首先点击菜单File->New->J2ME中的J2ME Midlet Suite , 然后Next。输入Project名称为ch01,其他项均选择默认,然后新建一个J2ME Midlet(并输入相应的报名com.dvs.ch01),就是一个入口程序,代码中输入
package com.dvs.ch01;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class Caculator extends MIDlet implements CommandListener {
private Display display;
private Form form=new Form("Caculator Exmaple Form");
private TextField tf1=new TextField("c1:", "", 10, TextField.DECIMAL);
private TextField tf2=new TextField("c2:", "", 10, TextField.DECIMAL);
private TextField tf3=new TextField("result:", "", 10, TextField.DECIMAL);
private Command cmdCommand=new Command("caculate", Command.OK, 0);
public Caculator() {
display=Display.getDisplay(this);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
form.append(tf1);
form.append(tf2);
form.append(tf3);
form.addCommand(cmdCommand);
form.setCommandListener(this);
display.setCurrent(form);
}
public void commandAction(Command arg0, Displayable arg1) {
if(arg0==cmdCommand)
{
double tmpC3=Double.parseDouble(tf1.getString().trim())+Double.parseDouble(tf2.getString().trim());
tf3.setString(tmpC3+"");
}
}
}
然后在此文件之上右键选择“Run As->Emulated J2MEMidlet”,即如图示
稍后出现手机模拟器,输入相应数字进行测试,效果如图
源代码下载地址:/UserFiles/ch01.rar