📄 clockcanvas.java
字号:
import java.io.IOException;
import java.util.Calendar;
import java.util.TimeZone;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
public class ClockCanvas extends Canvas implements Runnable {
private Image source;
private Image copy;
private Calendar cal;
private int imageWidth, imageHeight;
private int screenWidth, screenHeight;
private int hourLength = 36, minuteLength = 50, secLength = 58;
private int hour = 0, minute = 0, second = 0; //当前时间
private int hx, hy; //时针坐标
public ClockCanvas() {
try {
source = Image.createImage("/Clock.png");
copy = Image.createImage(this.getWidth(), this.getHeight());
Graphics g = copy.getGraphics();
imageWidth = source.getWidth();
imageHeight = source.getHeight();
screenWidth = this.getWidth();
screenHeight = this.getHeight();
TimeZone tz = TimeZone.getTimeZone("GMT+8:00");
cal = Calendar.getInstance();
g.drawImage(source, (screenWidth - imageWidth) / 2,
(screenHeight - imageHeight) / 2,
Graphics.TOP | Graphics.LEFT);
} catch (IOException e) {
e.printStackTrace();
}
Thread t = new Thread(this);
t.start();
}
protected void paint(Graphics g) {
g.drawImage(copy, 0, 0, Graphics.TOP | Graphics.LEFT);
g.setColor(0, 0, 0);
g.drawString(cal.getTime().toString(),0,0, Graphics.TOP | Graphics.LEFT);
second = (second + 1) % 60;
double secangle = Math.PI * second / 30;
int sx = screenWidth / 2 + (int) (secLength * Math.sin(secangle));
int sy = screenHeight / 2 - (int) (secLength * Math.cos(secangle));
//画秒针
g.setColor (0,0,0);
g.drawLine(sx, sy, screenWidth / 2, screenHeight / 2);
if (second % 60 == 0) {
minute = (minute + 1) % 60;
}
double minangle = Math.PI * minute / 30;
int mx = screenWidth / 2 + (int) (minuteLength * Math.sin(minangle));
int my = screenHeight / 2 - (int) (minuteLength * Math.cos(minangle));
//画分针
g.setColor(0,0,0);
g.drawLine(mx, my, screenWidth / 2, screenHeight / 2);
if (minute % 60 == 0) {
hour = (hour + 1) % 12;
}
double hourangle = Math.PI * hour / 6 + Math.PI * minute / 360;
hx = screenWidth / 2 + (int) (hourLength * Math.sin(hourangle));
hy = screenHeight / 2 - (int) (hourLength * Math.cos(hourangle));
//画时针
g.setColor (0,0,0);
g.drawLine(hx, hy, screenWidth / 2, screenHeight / 2);
}
public void run() {
hour = cal.get(Calendar.HOUR);
minute = cal.get(Calendar.MINUTE);
second = cal.get(Calendar.SECOND);
while (true) {
cal = Calendar.getInstance (TimeZone.getTimeZone("GMT+8:00"));
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -