📄 hellomidlet.java
字号:
package com.j2medev.chapter2;
import java.io.IOException;
import java.util.TimerTask;
import java.util.Timer;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class HelloMIDlet extends MIDlet implements CommandListener {
private Display display = null;
private Command exitCommand = new Command("Exit",Command.EXIT,1);
public void startApp() {
//初始化display和MyCanvas对象
display = Display.getDisplay(this);
MyCanvas canvas = new MyCanvas();
canvas.addCommand(exitCommand);
canvas.setCommandListener(this);
display.setCurrent(canvas);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command cmd,Displayable displayable){
if(cmd == exitCommand){
//退出应用程序
destroyApp(false);
notifyDestroyed();
}
}
class MyCanvas extends Canvas{
private Timer timer = new Timer();//定时器
private int x = 10;
private int y = 10;
private int width = 0;//画布的宽度
private int height = 0;//画布的高度
private Image img = null;
public MyCanvas(){
width = getWidth();
height = getHeight();
try{
img = Image.createImage("/helloworld.png");
}catch(IOException ex){
ex.printStackTrace();
}
}
public void paint(Graphics g){
//#if SonyEricsson_K700_Emu || A780
//# int color = g.getColor();
//# g.setColor(0xFFFFFF);
//# g.fillRect(0,0,width,height);
//# g.setColor(color);
//#else
//#endif
g.drawImage(img,x,y,Graphics.LEFT|Graphics.TOP);
}
//当Canvas显示到当前屏幕的时候此方法自动被调用
public void showNotify(){
//启动定时器,每100毫秒执行一次
timer.schedule(new TimerTask(){
private int dx = 2;
private int dy = 2;
public static final int SIGN = -1;
public void run(){
x = x + dx;
y = y + dy;
//判断图片是否到达屏幕边界
if(x+2+img.getWidth() > width || x-2 < 0)
dx = SIGN*dx;
if(y + 2 +img.getHeight()> height || y-4 < 0)
dy = SIGN*dy;
repaint();
serviceRepaints();
}
},0,100);
}
//当Canvas从当前屏幕删除的时候此方法被调用
public void hideNotify(){
timer.cancel();
img = null;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -