一、下列程序完成一个简单的画直线功能,按下触笔后,移动并松开触笔画条直线。
二、
三、代码
MIDPCanvas.java
package test1;
import javax.microedition.lcdui.*;
public class MIDPCanvas extends Canvas implements CommandListener{
privateMidlet midlet;
privateCommand cmd_exit,cmd_clear;
intsx,sy,cx,cy,oldcx,oldcy;
booleanblisclear,blisrelease,blisfirstpaint;
publicMIDPCanvas(Midlet midlet ) {
try {
// Set up this canvas to listen to commandevents
blisclear=false;
blisrelease=false;
blisfirstpaint=true;
sx=0;
sy=0;
cx=0;
cy=0;
oldcx=0;
oldcy=0;
this.midlet=midlet;
cmd_exit=new Command("退出",Command.EXIT,1);
cmd_clear=newCommand("清除",Command.SCREEN,1);
addCommand(cmd_exit);
addCommand(cmd_clear);
setCommandListener(this);
} catch(Exception e) {
e.printStackTrace();
}
}
public voidpaint(Graphics g) {
if (blisclear||blisfirstpaint){
blisfirstpaint=blisclear=false;
g.setColor(0, 0, 0);
g.fillRect(0,0,getWidth(),getHeight());
}
else{
if (!blisrelease){
g.setColor(0, 0, 0);
g.drawLine(sx, sy, oldcx,oldcy);
}
g.setColor(0, 255, 0);
g.drawLine(sx, sy, cx, cy);
}
}
protected void keyPressed(int keyCode) {
}
protected void keyReleased(int keyCode) {
}
protected void keyRepeated(int keyCode) {
}
protected void pointerDragged(int x, int y){
oldcx=cx;
oldcy=cy;
cx=x;
cy=y;
repaint();
}
protected void pointerPressed(int x, int y){
blisrelease=false;
sx=x;
sy=y;
}
protected void pointerReleased(int x, int y){
blisrelease=true;
cx=x;
cy=y;
repaint();
}
public voidcommandAction(Command command, Displayable displayable) {
if (command==cmd_exit){
midlet.exitApp();
}
else if(command==cmd_clear){
blisclear=true;
repaint();
}
}
}
Midlet.java
package test1;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Midlet extends MIDlet {
privateDisplay display;
private MIDPCanvas midpcanvas;
publicMidlet(){
display=Display.getDisplay(this);
midpcanvas=newMIDPCanvas(this);
}
public voidstartApp() {
display.setCurrent(midpcanvas);
}
publicvoid pauseApp() {
}
public voidexitApp(){
destroyApp(true);
notifyDestroyed();
}
publicvoid destroyApp(boolean unconditional) {
}
}