📄 timerdemo.java
字号:
package ch09.section02;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;
public class TimerDemo
extends MIDlet {
Display display;
StarField field = new StarField();
FieldMover mover = new FieldMover();
Timer timer = new Timer();
public TimerDemo() {
display = Display.getDisplay(this);
}
protected void destroyApp(boolean unconditional) {
}
protected void startApp() {
display.setCurrent(field);
//时间延迟100毫秒
timer.schedule(mover, 100, 100);
}
protected void pauseApp() {
}
public void exit() {
//停止滚动退出应用程序
timer.cancel();
destroyApp(true);
notifyDestroyed();
}
//该类实现动画
class FieldMover
extends TimerTask {
public void run() {
field.scroll();
}
}
class StarField
extends Canvas {
//定义星空显示区域
int height;
int width;
int[] stars;
//随即产生星星数量
Random generator = new Random();
boolean painting = false;
public StarField() {
height = getHeight();
width = getWidth();
stars = new int[height];
for (int i = 0; i < height; ++i) {
stars[i] = -1;
}
}
//实现区域连续向下滚动
public void scroll() {
if (painting) {
return;
}
for (int i = height - 1; i > 0; --i) {
stars[i] = stars[i - 1];
}
stars[0] = (generator.nextInt() %
(3 * width)) / 2;
if (stars[0] >= width) {
stars[0] = -1;
}
repaint();
}
protected void paint(Graphics g) {
painting = true;
g.setColor(0, 0, 0);
g.fillRect(0, 0, width, height);
g.setColor(255, 255, 255);
for (int y = 0; y < height; ++y) {
int x = stars[y];
if (x == -1) {
continue;
}
//绘制一个简单星星,以一条短线代表
g.drawLine(x, y, x, y);
}
painting = false;
}
protected void keypressed(int keycode) {
exit();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -