doodle.java

来自「《Java ME手机应用开发大全》源码 書籍內容簡介: http://www」· Java 代码 · 共 116 行

JAVA
116
字号
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class Doodle extends MIDlet
{
  private Display  display;      
  private DoodleCanvas canvas;    
  public Doodle()
  {
	 //获取MIDlet的Display对象实例
    display = Display.getDisplay(this);
	//声明Canvas屏幕对象
    canvas  = new DoodleCanvas(this);
  }
  protected void startApp()
  {
    display.setCurrent( canvas );
  }
  protected void pauseApp()
  { }

  protected void destroyApp( boolean unconditional )
  { }
  public void exitMIDlet()
  {
    destroyApp(true);
    notifyDestroyed();
  }
}

/*--------------------------------------------------
* 声明画布屏幕类DoodleCanvas
*-------------------------------------------------*/
class DoodleCanvas extends Canvas implements CommandListener
{
  //声明软键对象
  private Command cmExit;          
  private Command cmClear; 
  //声明指针按下的位置
  private int startx = 0,   
              starty = 0,
  //声明指针的当前位置
              currentx = 0, 
              currenty = 0;
  private Doodle midlet;
  private boolean clearDisplay = false;

  /*--------------------------------------------------
  * 画布类的构造函数
  *-------------------------------------------------*/
  public DoodleCanvas(Doodle midlet)
  {
    this.midlet = midlet;
    cmExit = new Command("Exit", Command.EXIT, 1);
    cmClear = new Command("Clear", Command.SCREEN, 1);    
    addCommand(cmExit);
    addCommand(cmClear);
    setCommandListener(this);
  } 

  /*--------------------------------------------------
  * 定义paint()方法
  *-------------------------------------------------*/
  protected void paint(Graphics g)
  {
    // 清除屏幕
    if (clearDisplay)
    {
      g.setColor(255, 255, 255);
      g.fillRect(0, 0, getWidth(), getHeight());
      clearDisplay = false;
      startx = currentx = starty = currenty = 0;
      return;
    }
    // 设置画笔颜色
    g.setColor(0, 0, 0);
    // 画出直线
    g.drawLine(startx, starty, currentx, currenty);
    // 设置新的起始点
    startx = currentx;
    starty = currenty;
  }

  /*--------------------------------------------------
  * 软键的事件响应处理方法
  *-------------------------------------------------*/  
  public void commandAction(Command c, Displayable d)
  {
    if (c == cmExit)
      midlet.exitMIDlet();
    else if (c == cmClear)
    {
      clearDisplay = true; 
      repaint();
    }
  }

  /*--------------------------------------------------
  * 指针按下的事件处理程序
  *-------------------------------------------------*/  
  protected void pointerPressed(int x, int y)
  {
    startx = x;
    starty = y;
  }

  /*--------------------------------------------------
  * 指针拖放的事件处理程序
  *-------------------------------------------------*/  
  protected void pointerDragged(int x, int y)
  {
    currentx = x;
    currenty = y;       
    repaint();
  } 
} 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?