J2ME入门学习(二)
这次我开始进入了J2ME的开发,当然还是入门级的。
首先说说开发工具:在安装了J2SDK后开始安装Netbeans IDE4.1。之后安装Mobility Pack4.1,这是Netbeans IDE的一个软件包。工具安装好后,来开发我的第一个程序。 首先点击“文件”新建一个项目。然后类别选“移动”,项目选“Moblie Application”
点击下一步,如下图
填写好保存的路径和项目的位置,点击下一步,
按图选择好配置和简表,点击“完成”。
在项目中创建一个Java包,输入com.j2medev.netbeans
点击文件,在主目录下添加新的文件夹res,并将相应的图片粘贴到相应的文件夹下
此时为了避免出现无法找到资源的问题,要把res文件加入到项目绑定资源中。在项目视图中右键单击myMobileProj1选择“属性”,然后选“库和资源”——添加文件夹,把res目录加入到绑定资源中
现在可以开始编写代码了,代码如下:
package com.j2medev.netbeans;
/*
* TurboMidlet.java
*
* Created on
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
*
* @author kidd
* @version
*/
public class TurboMidlet extends MIDlet implements CommandListener{
private Display display = null;
private Form mainForm = null;
public static final Command exitCommand = new Command("exit",Command.OK, 1);
public void startApp() {
if(display == null){
display = Display.getDisplay(this);
}
mainForm = new Form("TurboMIDlet");
Image img = getImage("JavaPowered-8.png");
mainForm.append(img);
String text = "";
try{
text = getText("j2medev.txt");
}
catch(IOException ex){
text = "error";
}
mainForm.append("\n" + text);
mainForm.addCommand(exitCommand);
mainForm.setCommandListener(this);
display.setCurrent(mainForm);
}
private Image getImage(String name){
Image img = null;
try{
img = Image.createImage("/images/" + name);
}
catch(IOException ex){
ex.printStackTrace();
}
return img;
}
private String getText(String name)throws IOException{
InputStream is = getClass().getResourceAsStream("/text/" + name);
if(is != null){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch = 0;
while((ch = is.read()) != -1){
baos.write(ch);
}
byte[] text = baos.toByteArray();
baos.close();
return new String(text,"UTF-8");
}
else{
return null;
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command cmd,Displayable displayabel){
if(cmd == exitCommand){
destroyApp(false);
notifyDestroyed();
}
}
}
此时点击F6运行程序