J2ME的一些模版

原创 2011年07月21日 09:24:29

音乐播放模版:

/**
 * 类说明:音乐的控制
 * ware audio files  audio/x-wav
 * au                audio/basic
 * mp3               audio/mpeg
 * midi              audio/midi
 * tone              audio/x-tone-sep
 * mpeg              video/mpeg
 * @author 作者: User
 * @version 创建时间:2011-3-22 下午10:02:59
 */

import java.io.InputStream;

import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.VolumeControl;

public class Music {
    private static Music instance;

    private Player player;// 创建一个音乐播放器
    private VolumeControl volumeControl = null;// 声音控制
    private int volume = 50;// 音量的初始值
    private static final int MAX = 100;// 音量最大值
    private static final int MIN = 0;// 音量最小值
    private boolean isplay = false;//是否真正播放

    private Music() {

    }

    // 采用单例模式 返回本类对象
    static Music getInstance() {
        if (instance == null) {
            instance = new Music();
        }
        return instance;
    }

    // 播放音乐
    public void playMusic() {
        player = createPlayer("/city.mid", "audio/midi");// 创建音乐播放器
        volumeControl = (VolumeControl) player.getControl("VolumeControl");// 得到音乐控制器
        isplay = true;
        startPlayer(player);// 开始播放音乐
    }

    // 停止音乐播放
    public void stopMusic() {
        try {
            if (player != null)
                player.stop();
            player = null;
            isplay = false;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 加大音量
    public void addVolume() {
        if (volumeControl != null) {
            volume += 10;
            if (volume > MAX)
                volume = MAX;
            volumeControl.setLevel(volume);
        }
    }

    public boolean isPlay() {
        return isplay;
    }

    // 减小音量
    public void subVolume() {
        if (volumeControl != null) {
            volume -= 10;
            if (volume < MIN)
                volume = MIN;
            volumeControl.setLevel(volume);
        }
    }
    
    // 设置音量
    public void setVolume(int volue) {
        if (volumeControl != null) {
            volumeControl.setLevel(volue);
        }
    }
    // 开始播放
    private void startPlayer(Player p) {
        if (p != null) {
            try {
                p.stop();
                p.setLoopCount(-1);
                p.start();
            } catch (MediaException me) {
                me.printStackTrace();
            }
        }
    }

    // 创建音乐播放器
    private Player createPlayer(String filename, String format) {
        Player p = null;
        try {
            InputStream is = getClass().getResourceAsStream(filename);// 得到音乐文件输入流
            p = Manager.createPlayer(is, format);
            p.prefetch();
        } catch (Exception ioe) {
            ioe.printStackTrace();
        }
        return p;
    }
}


 

java字符串解析 将字符串解析成字符数组

//字符串解析
    private String[] stringAnalytical(String str, String divisionChar) {
        String string[];
       int i = 0; 
        StringTokenizer tokenizer = new StringTokenizer(str, divisionChar);
        string = new String[tokenizer.countTokens()];// 动态的决定数组的长度
         while (tokenizer.hasMoreTokens()) {
            string[i] = new String();
            string[i] = tokenizer.nextToken();
            i++;
        }
        return string;// 返回字符串数组
    }


 

j2me中字符串的解析,将字符串根据特定的字符解析成字符数组:

// 字符串解析,将字符串转根据分割符换成字符串数组
    private String[] stringAnalytical(String string, char c) {
        int i = 0;
        int count = 0;

        if (string.indexOf(c) == -1)
            return new String[] { string };// 如果不含分割符则返回字符本身
        char[] cs = string.toCharArray();
        int length = cs.length;
        for (i = 1; i < length - 1; i++) {// 过滤掉第一个和最后一个是分隔符的情况
            if (cs[i] == c) {
                count++;// 得到分隔符的个数
            }
        }
        String[] strArray = new String[count + 1];
        int k = 0, j = 0;
        String str = string;
        if ((k = str.indexOf(c)) == 0)// 去掉第一个字符是分隔符的情况
            str = str.substring(k + 1);
        if (str.indexOf(c) == -1)// 检测是否含分隔符,如果不含则返回字符串
            return new String[] { str };
        while ((k = str.indexOf(c)) != -1) {// 字符串含分割符的时候
            strArray[j++] = str.substring(0, k);
            str = str.substring(k + 1);
            if ((k = str.indexOf(c)) == -1 && str.length() > 0)
                strArray[j++] = str.substring(0);
        }
        return strArray;
    }


进度条实例模板

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;



public class GaugeUI extends Form implements CommandListener {
    private static final int MAX = 8;
    private static final int LEVELS = 8;
    int current = 0;
    Gauge gauge;
    Command stopCommand;
    boolean stop;
    boolean stopped;

    /** Creates a new instance of GaugeObserverUI */
    public GaugeUI() {
        super("");
        // 创建一个进度条
        gauge = new Gauge("", false, MAX, 0);
        stopCommand = new Command("停止", Command.STOP, 10);
        addCommand(stopCommand);
        append(gauge);
        setCommandListener(this);

    }

    // 初时化进度条
    public void init(String note, boolean stop) {
        gauge.setValue(0);
        setNote(note);
        setStop(stop);
        stopped = false;
    }

    // 进度条标题
    public void setNote(String note) {
        setTitle(note);
    }

    // 是否停止
    public boolean isStop() {
        return stop;
    }

    // 设置进度条停止
    public void setStop(boolean stop) {
        this.stop = stop;
    }

    // 是否已停止
    public boolean isStopped() {
        return stopped;
    }

    // 更新进度条
    public void updateGauge() {
        current = (current + 1) % LEVELS;
        gauge.setValue(current * MAX / LEVELS);
    }

    // 处理监听
    public void commandAction(Command c, Displayable d) {
        if (c == stopCommand) {
            stopped = true;
            stop();
        }
    }

    // 停止时事件处理
    public void stop() {
        
    }
}


 

rms模版

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.rms.RecordComparator;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordFilter;
import javax.microedition.rms.RecordStore;


public class RmsPricatis extends MIDlet {

    public RmsPricatis() {
        // TODO Auto-generated constructor stub
    }

    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 {
        try {
            RecordStore rs = RecordStore.openRecordStore("rj", true);
            /* rs.addRecord("张三".getBytes(), 0, 4);
             rs.addRecord("李四".getBytes(), 0, 4);
             rs.addRecord("王五".getBytes(), 0, 4);
             rs.addRecord("王强".getBytes(), 0, 4);
             rs.addRecord("钱王六".getBytes(), 0, 6);*/
            RecordEnumeration re = rs.enumerateRecords(new Filter(), new Compare(), false);
            while (re.hasNextElement()) {
                   System.out.println(new String(rs.getRecord(re.nextRecordId())));
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
//过滤器
    class Filter implements RecordFilter {

        public boolean matches(byte[] b) {
            String name = new String(b);
            if (name.indexOf("王") >= 0) {
                return true;
            }
            return false;
        }
    }
//    比较器
    class Compare implements RecordComparator{

        public int compare(byte[] b1, byte[] b2) {
            String  s1 = new String(b1);
            String  s2 = new String(b2);
            if(s1.length()>s2.length())
                return RecordComparator.FOLLOWS;
            else if(s1.length()==s2.length())
                return RecordComparator.EQUIVALENT;
            else 
                return RecordComparator.PRECEDES;
        }
        
    }
}


 

j2me中将对象转换成字节数组的方法

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class PhoneCard {
    private int password;// 电话密码
    private long cardNumber;// 电话卡卡号
    private double balance;// 电话卡余额
    private String conncetNumber;// 电话卡接入号码
    private boolean connected;// 电话是否接通

    //将对象转换成字节数组
    public byte[] PhoneCard2Byte() throws IOException{
        byte[] phonecard;// 用于存放转换后的对象
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// 字节输出流
        DataOutputStream dos = new DataOutputStream(baos);// 数据输出流用于包装字节输出流
        dos.writeInt(password);
        dos.writeLong(cardNumber);
        dos.writeDouble(balance);
        dos.writeUTF(conncetNumber);
        dos.writeBoolean(connected);
        phonecard = baos.toByteArray();// 将写入的数据转换成字节数组
        dos.close();
        baos.close();
        return phonecard;
    }
    //将字节数组装换成PhoneCard对象
    public static  PhoneCard byte2PhonCard(byte[] phonecard)throws IOException{
        PhoneCard pc = new PhoneCard();
        ByteArrayInputStream bais = new ByteArrayInputStream(phonecard);// 字节输入流
        DataInputStream dis = new DataInputStream(bais);// 数据输入流用于包装字节输入流
        // 从流中读取数据,顺序要和写入时一至
        pc.setPassword(dis.readInt());
        pc.setCardNumber(dis.readLong());
        pc.setBalance(dis.readDouble());
        pc.setConncetNumber(dis.readUTF());
        pc.setConnected(dis.readBoolean());
        dis.close();
        bais.close();
        return pc;// 返回PhoneCard对象
        
    }

    // 返回对象的字符串类型
    public String toString(){
        return "电话密码 : " + password + "     电话卡号 :" + cardNumber + "    电话余额 :"
                + balance + "    接入号码 :" + conncetNumber + "    接通否 :"
                + connected;
    }
    public int getPassword() {
        return password;
    }

    public void setPassword(int password) {
        this.password = password;
    }

    public long getCardNumber() {
        return cardNumber;
    }

    public void setCardNumber(long cardNumber) {
        this.cardNumber = cardNumber;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public String getConncetNumber() {
        return conncetNumber;
    }

    public void setConncetNumber(String conncetNumber) {
        this.conncetNumber = conncetNumber;
    }

    public boolean isConnected() {
        return connected;
    }

    public void setConnected(boolean connected) {
        this.connected = connected;
    }
    
}



 

j2me联网测试

import java.io.DataInputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;


public class Test7_1Http extends MIDlet {
private Form form = null;
private Display display = null;
    public Test7_1Http() {
        form = new Form("连网测试");
        display = Display.getDisplay(this);
    }
    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
    }

    protected void pauseApp() {
    }

    protected void startApp() throws MIDletStateChangeException {
        try {
            HttpConnection connection = (HttpConnection)Connector.open("http://localhost:8080/pdsu.html");
            
            System.out.println(connection.getResponseCode());//得到连接状态
            System.out.println(connection.getResponseMessage());//得到连接响应的消息
            
            System.out.println(connection.getHost());//得到主机地址
            System.out.println(connection.getPort());//得到连接的断口号
            System.out.println(connection.getProtocol());//得到连接的协议
            System.out.println(connection.getURL());
            System.out.println(connection.getRequestMethod());//得到连接方式     默认get
            
            DataInputStream dis = connection.openDataInputStream();
             byte message[];
             int length = (int)connection.getLength();
             message = new byte[length];
             dis.readFully(message);
             form.append(new String(message));
             display.setCurrent(form);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


例子

j2me Socket例子

 

客户端:

import java.io.DataOutputStream;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
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 Test7_2Client extends MIDlet implements CommandListener {
    private Form form = null;
    private Display display = null;
    private TextField field = null;
    private Command send = null;
    private SocketConnection sc = null;

    public Test7_2Client() {
        form = new Form("客户端");
        display = Display.getDisplay(this);
        field = new TextField("文本信息", "", 100, TextField.ANY);
        send = new Command("发送", Command.OK, 1);
        form.setCommandListener(this);
        form.addCommand(send);
        form.append(field);
    }

    protected void startApp() throws MIDletStateChangeException {
        display.setCurrent(form);
    }

    public void commandAction(Command c, Displayable d) {
        if (c == send) {
            new SendMessage().start();
        }
    }

    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
    }

    protected void pauseApp() {
    }

    class SendMessage extends Thread {
        private DataOutputStream dos = null;

        public void run() {
            
            try {
                sc = (SocketConnection) Connector
                        .open("socket://localhost:50000");
                dos = sc.openDataOutputStream();
                dos.writeUTF(field.getString());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (dos != null)
                        dos.close();
                    if (sc != null)
                        sc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
        }
    }

}


服务器端:

import java.io.DataInputStream;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import javax.microedition.io.SocketConnection;
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 Test7_2Server extends MIDlet implements CommandListener {
    private Form form = null;
    private Display display = null;
    private TextField field = null;
    private Command accept = null;
    private ServerSocketConnection ssc = null;
    private SocketConnection sc = null;
    private String message = null;

    public Test7_2Server() {
        form = new Form("服务端");
        display = Display.getDisplay(this);
        field = new TextField("文本信息", "", 100, TextField.ANY);
        accept = new Command("接受", Command.OK, 1);
        form.setCommandListener(this);
        form.addCommand(accept);
        form.append(field);
        new AcceptMessage().start();
    }

    public void commandAction(Command c, Displayable d) {
        if (c == accept) {
            field.setString(message);
        }
    }

    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
    }

    protected void pauseApp() {
    }

    protected void startApp() throws MIDletStateChangeException {
        display.setCurrent(form);
    }

    class AcceptMessage extends Thread {
        private DataInputStream dis = null;

        public void run() {
            while (true) {
                try {
                    ssc = (ServerSocketConnection) Connector
                            .open("socket://:50000");
                    sc = (SocketConnection) ssc.acceptAndOpen();
                    dis = sc.openDataInputStream();
                    message = dis.readUTF();
                    System.out.println("Server : " + message);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (dis != null)
                            dis.close();
                        if (sc != null)
                            sc.close();
                        if (ssc != null)
                            ssc.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}



j2me多线程应用实例

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class twoStrings extends MIDlet {
    Display display;
    Form form;
    public String promote = "";
    StringItem s1 = new StringItem("string1", "" + promote);
    StringItem s2 = new StringItem("string1", "" + promote);

    public twoStrings() {
    }

    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
    }

    protected void pauseApp() {

    }

    protected void startApp() throws MIDletStateChangeException {
        display = Display.getDisplay(this);
        form = new Form("");
        form.append(s1);
        form.append(s2);
        display.setCurrent(form);
        Thread1 th1 = new Thread1();
        th1.start();
        Thread2 th2 = new Thread2();
        new Thread(th2).start();

    }

    class Thread1 extends Thread {
        int i = 1;
        public void run() {
            while (true) {
                promote = Integer.toString(i);
                i++;
                s1.setText(promote);
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
            }
        }
    }

    class Thread2 implements Runnable {
        int i = 1;
        public void run() {
            while (true) {
                promote = Integer.toString(i);
                i++;
                s2.setText(promote);
                try {
                    Thread.sleep(2000);
                } catch (Exception e) {
                }
            }
        }
    }
}


 用Canvas画的菜单:

import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class MainMIDlet extends MIDlet {

public MainMIDlet() {
}

protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}

protected void pauseApp() {

}

protected void startApp() throws MIDletStateChangeException {
  Display.getDisplay(this).setCurrent(new MenuCanvas());
}
}


package test;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

public class MenuCanvas extends Canvas{
public Rect[] rect = new Rect[4];//菜单选项RECT;
public Rect text_Rect = null;//文本框RECT;
public Rect choce_Rect = null;//按钮RECT;
public Rect big_Rect = null;//菜单选项外的RECT;
public boolean isClicked = false;//是否点击"选择"
public int clicked_Num = -1;//选择了哪项
// public Graphics bg = null;
// public Image buff = null;
public final String[] menu_str = new String[]{"选 择", "比翼双飞", "龙飞凤舞", "双龙戏珠", "好彩当头"};

public MenuCanvas()
{
intiRect();
}

// public void buffer()
// {
// buff = Image.createImage(big_Rect.w, big_Rect.h);
// bg = buff.getGraphics();
// }

protected void paint(Graphics g) {
// TODO Auto-generated method stub
  g.setColor(255, 255, 255);
  g.fillRect(0, 0, this.getWidth(), this.getHeight());
  drawRect(g);
}

public void drawRect(Graphics g)
{
text_Rect.drawString(g);
choce_Rect.drawString(g);
big_Rect.drawString(g);
for(int i = 0; i < rect.length; i++)
{
rect[i].drawString(g);
}
}

public void intiRect()
{
text_Rect = new Rect(40, 40, 80, 20, null, true);
choce_Rect = new Rect(130, 40, 40, 20, menu_str[0], false);
big_Rect = new Rect(40, 60, 80, 80, null, false);
for(int i = 0; i < rect.length; i++)
{
rect[i] = new Rect(40, (60 + i * 20), 80, 20, null, false);
}
}

protected void keyPressed(int keyCode) {
super.keyPressed(keyCode);
}

protected void pointerPressed(int x, int y) {
super.pointerPressed(x, y);
if(choce_Rect.isClicked(x, y))
{
isClicked = !isClicked;
if(isClicked)
{
choce_Rect.isRect = true;
big_Rect.isRect = true;
for(int i = 0; i < rect.length; i++)
{
rect[i].menu_str = menu_str[i + 1];
rect[i].calculateStringWH();
}
}
else
{
choce_Rect.isRect = false;
big_Rect.isRect = false;
text_Rect.menu_str = null;
for(int i = 0; i < rect.length; i++)
{
rect[i].menu_str = null;
rect[i].isRect = false;
}
}
}
else if(big_Rect.isClicked(x, y))
{
for(int i = 0; i < rect.length; i++)
{
if(rect[i].isClicked(x, y))
{
clicked_Num = i;
rect[i].isRect = true;
text_Rect.menu_str = menu_str[i + 1];
text_Rect.calculateStringWH();
//可以在这里写要跳转的页面方法
}
else
{
rect[i].isRect = false;
}
}
}
else
{
choce_Rect.isRect = false;
isClicked = false;
big_Rect.isRect = false;
text_Rect.menu_str = null;
for(int i = 0; i < rect.length; i++)
{
rect[i].menu_str = null;
rect[i].isRect = false;
}
}
repaint();
}
}


package test;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

public class Rect {
public int x = 0;
public int y = 0;
public int w = 0;
public int h = 0;
public int s_W = 0;
public int s_H = 0;
public int space_X = 0;
public int space_Y = 0;
public boolean isRect = false;
public String menu_str = null;
public Font font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_LARGE);
public Rect(int x, int y, int w, int h, String str, boolean isRect)
{
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.menu_str = str;
this.isRect = isRect;
calculateStringWH();
}
public boolean isClicked(int x, int y)
{
if ((x >= this.x && x <= (this.x + this.w))
&& ((y >= this.y && y <= (this.y + this.h)))) {
  return true;
}
return false;
}
public void drawString(Graphics g)
{
g.setColor(0, 0, 0);
if(isRect)
{
g.drawRect(x, y, w, h);
}
if(menu_str != null)
{
g.setFont(font);  
g.drawString(menu_str, (x + space_X), (y + space_Y), Graphics.TOP | Graphics.LEFT);
}
}
public void calculateStringWH()
{
if(menu_str != null)
{
s_W = font.stringWidth(menu_str);
s_H = font.getBaselinePosition();
if(this.w > s_W)
{
space_X = (this.w - s_W) >> 1;
}
if(this.h > s_H)
{
space_Y = (this.h - s_H) >> 1;
}
}
}
}


 

画出游戏菜单的方法

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.lcdui.*;
import java.util.Vector;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

public class MenuMIDlet extends MIDlet {
 private MenuCanvas mc;

 public static MenuMIDlet inc;

 public MenuMIDlet() {
  mc = new MenuCanvas();
  inc = this;
 }

 protected void destroyApp(boolean arg0) throws MIDletStateChangeException {

 }

 protected void pauseApp() {

 }

 protected void startApp() throws MIDletStateChangeException {
  Display.getDisplay(this).setCurrent(mc);

 }

}
class MenuCanvas extends Canvas {
 private final int LOGO = 0;

 private final int MENU = 1;

 private final int GAME = 2;

 private final int INFO = 3;

 private final int HELP = 4;

 private final int EXIT = 5;// 常量表示各个状态

 private int zt;// 状态变量

 private int width, height;// 屏幕宽和高

 private Font ft;// 字体

 private String smenu[] = { "new game", "infomation", "hlep", "exit" };// 菜单文字

 private String sinfo = "    作者:XXX\n" + "    这些内容你慢慢想";// 介绍文字

 private String info[];// 保存介绍文字

 private String shelp = "2,8,4,9控制上,下,左,右,确定/5键确定选项,等等等等.这些地方你也自己想吧";// 帮助文字

 private String help[];// 保存帮助文字

 private int n, m;

 public MenuCanvas() {
  width = getWidth();
  height = getHeight();
  ft = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_LARGE);
  switchZ(MENU);
 }

 public void switchZ(int zt) {//改变状态时要做的事
  switch (zt) {
  case LOGO:
   // 我这里就不做LOGO了.
   break;
  case MENU:
   break;
  case GAME:
   // 游戏等菜单做完了再教你做游戏,一步步来
   break;
  case INFO:
   info = format(sinfo, width, ft);
   break;
  case HELP:
   help = format(shelp, width, ft);
   break;
  case EXIT:
   m = 0;
   break;
  }
  this.zt = zt;
 }

 protected void paint(Graphics g) {
  g.setClip(0, 0, width, height);
  g.setColor(0x000000);
  g.fillRect(0, 0, width, height);

  switch (zt) {
  case LOGO:
   break;
  case MENU:
   drawmenu(g);
   break;
  case INFO:
   drawinfo(g);
   break;
  case HELP:
   drawhelp(g);
   break;
  case EXIT:
   drawexit(g);
   break;
  }

 }

 private void drawexit(Graphics g) {
  g.setColor(0x00ff00);
  g.setFont(ft);
  g.drawString("are you exit", width / 2, height / 2 - 50,
    Graphics.HCENTER | Graphics.TOP);
  if (m == 1) {
   g.setColor(0xff0000);
  } else {
   g.setColor(0xffffff);
  }
  g.drawString("yes", 35, height - 50, 20);
  if (m == 0) {
   g.setColor(0xff0000);
  } else {
   g.setColor(0xffffff);
  }
  g.drawString("no", width - 35, height - 50, 24);
 }

 private void drawhelp(Graphics g) {
  g.setColor(0xffffff);
  g.setFont(ft);
  for (int i = 0; i < help.length; i++) {
   g.drawString(help[i], 0, i * ft.getHeight(), 20);
  }

 }

 private void drawinfo(Graphics g) {
  g.setColor(0xffffff);
  g.setFont(ft);
  for (int i = 0; i < info.length; i++) {
   g.drawString(info[i], 0, i * ft.getHeight(), 20);
  }
 }

 public void drawmenu(Graphics g) {
  g.setColor(0x0000ff);
  g.setFont(ft);
  for (int i = 0; i < smenu.length; i++) {
   g.drawString(smenu[i], width / 2, height / 2 + i * ft.getHeight()
     - 50, Graphics.HCENTER | Graphics.TOP);
  }
  g.setColor(0xff0000);
  g.drawRect(width / 2 - 50, height / 2 + n * ft.getHeight() - 50, 100,
    ft.getHeight());
 }

 public 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;
 }

 protected void keyPressed(int arg0) {
  repaint();
  switch (this.getGameAction(arg0)) {
  case FIRE:
   switch (zt) {
   case MENU:
    switch (n) {
    case 0:
     // 新游戏没写
     break;
    case 1:
     switchZ(INFO);
     break;
    case 2:
     switchZ(HELP);
     break;
    case 3:
     switchZ(EXIT);
     break;
    }
    break;
   case INFO:
    switchZ(MENU);
    break;
   case HELP:
    switchZ(MENU);
    break;
   case EXIT:
    switch (m) {
    case 0:
     switchZ(MENU);
     break;
    case 1:
     MenuMIDlet.inc.notifyDestroyed();
     break;
    }
   }
   break;
  case UP:
   switch (zt) {
   case MENU:
    n--;
    if (n < 0) {
     n = 3;
    }
    break;
   }
   break;
  case DOWN:
   switch (zt) {
   case MENU:
    n++;
    if (n > 3) {
     n = 0;
    }
    break;
   }
   break;
  case LEFT:
   switch (zt) {
   case EXIT:
    m++;
    if (m > 1) {
     m = 0;
    }
    break;
   }
   break;
  case RIGHT:
   switch (zt) {
   case EXIT:
    m--;
    if (m < 0) {
     m = 1;
    }
    break;
   }
   break;
  }
 }
}


 

J2ME飞机游戏程序模版

  • 2009年01月13日 14:58
  • 8KB
  • 下载

用J2ME在移动设备上实现动画(1) (2007-04-11 11:47)

使用MIDP(Mobile Information Device Profile)的开发人员经常会抱怨用些什么办法才可以在一个MIDlet上显示动画。MIDP 1.0 没有直接提供对动画的支持(M...

通过J2ME的录音功能实现简易示波器

本文来自http://blog.csdn.net/hellogv/ ,引用必须注明出处!              早就有人通过PC声卡的输入(麦克风孔)来做模拟示波器,但是用手机来实现的比较...

【贪吃蛇—Java程序员写Android游戏】系列 3. 用J2ME实现Android的Snake Sample详解

本次会详细讲解将Android的Snake Sample移植到J2ME上,从而比较二者的区别和联系。 在《1.Android SDK Sample-Snake详解》中,我们已经详细介绍了Andr...
  • deaboway
  • deaboway
  • 2011年04月10日 17:51
  • 19869

j2me 如何进行设计?

J2ME 在设计其规格的时候,遵循着「对于各种不同的装置而造出一个单一的开发系统是没有意义的事」这个基本原则。 于是 JAVA ME 先将所有的嵌入式装置大体上区分为两种 :一种是运算功能有限、电力...
  • ggabcda
  • ggabcda
  • 2017年08月05日 09:57
  • 74

j2me学习笔记【13】——创建矩形框、圆角矩形以及填充颜色小例子

    可以通过标记左上角和右下角的坐标来定义矩形的尺寸。在画布上可以绘制4中矩形,分别是矩形框、填充矩形、圆角矩形框、圆角填充矩形。    可以调用drawRect()方法创建矩形框,调用fillR...

怎么获取J2ME软件签名证书

数字证书就是标志网络用户身份信息的一系列数据,用来在网络通讯中识别通讯各方的身份,即要在Internet上解决"我是谁"的问题,就如同现实中我们每一个人都要拥有一张证明个人身份的身份证或驾驶执照一样,...

认识jad 证书,j2me签名相关注意事项

教你一步步认识jar(附java权限XX、后台等)http://bbs.dospy.com/thread-6531845-1-236-28.html  j2me签名相关注意事项 我们得到一个证书后就可...

Eclipse搭建J2ME开发环境

sun_java_wireless_toolkit-2_5_2-ml-windows.exe 下载地址:http://www.oracle.com/technetwork/java/download...

J2ME图片半透明处理(使用图片像素)(仅部分手机支持)

其实就是把一张图的argb值都取出来存在一个整型数组里(用Image对象的getRGB方法),然后用循环逐一修改argb值得最高位(最高位 的8个2进制值代表了阿尔法通道也不什么的,反正就是透明度),...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:J2ME的一些模版
举报原因:
原因补充:

(最多只允许输入30个字)