我的J2ME编程练习(8)——Canvas3

/*
 * Canvas3let.java
 *
 * Created on 2005年4月20日, 下午3:55
 */

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
 *
 * @author  Administrator
 * @version
 */
public class Canvas3let extends MIDlet implements CommandListener{
    private Display aDisplay;
   
    private Command okCommand;
    private Command exitCommand;
    private Command backCommand;
   
    private TextBox aTextBox;
   
    private Alert showAlert;
   
    private Image showImage;
   
    private MyCanvas aMyCanvas;
   
    public Canvas3let(){
        exitCommand=new Command("退出",Command.EXIT,1);
        okCommand=new Command("进入",Command.OK,1);
        try{
            showImage=Image.createImage("/sohu.png");
        }
        catch(Exception e){}
       
        showAlert=new Alert("Loading...","载入中……",showImage,AlertType.INFO);
       
       
        aTextBox=new TextBox("KeyPress Test",
                "按下进入键后,即可进入显示界面,可以显示所按按键",
                25,TextField.ANY);
       
        aTextBox.addCommand(exitCommand);
        aTextBox.addCommand(okCommand);
        aTextBox.setCommandListener(this);
       
       
       
    }
    public void startApp() {
        aDisplay=Display.getDisplay(this);
        aDisplay.setCurrent(aTextBox);
    }
   
    public void pauseApp() {
    }
   
    public void destroyApp(boolean unconditional) {
    }
   
    public void commandAction(Command c , Displayable d){
        if(c==exitCommand){
            destroyApp(false);
            notifyDestroyed();
        }
        else if (c==okCommand){
           
            aMyCanvas=new MyCanvas();
            aDisplay.setCurrent(aMyCanvas);
        }
           
        }
   
   
   
    public class MyCanvas extends Canvas implements CommandListener{
       
        String keyName="";
        public MyCanvas(){
            backCommand=new Command("后退",Command.EXIT,1);
            addCommand(backCommand);
            setCommandListener(this);
        }
       
        public void paint(Graphics g){
           //清除屏幕
            g.setColor(0xFFFFFF);
            g.fillRect(0,0,getWidth(),getHeight());
           
            //设置字体颜色并画出所按键的名称
            g.setColor(0);
            g.drawString(keyName,100,100,Graphics.LEFT|Graphics.BOTTOM);
        }
       
        public void commandAction(Command c , Displayable d){
            if (c==backCommand){
                hideNotify();
                //aDisplay.setCurrent(aTextBox);
            }
           
        }
       
        public void keyPressed(int keyCode){
            keyName=getKeyName(keyCode);
            repaint();
        }
        
        protected void hideNotify(){
            aDisplay.setCurrent(showAlert,aTextBox);
        }
    }
}

通过这个程序,主要练习了keyPress的用法。此外,还有hideNotify()的用法,但showNotify()的用法还不是很清楚。

hideNotify()是在画布被从显示屏移除后,实现立刻调用该方法。

shoNotify()是在画布显示在显示屏之前系统将先调用该方法。

你可能感兴趣的:(J2ME)