[color=green]J2ME关于Lwuit应用的钟表ClockWidget程序[/color]
package com.mopietek;
import java.util.Calendar;
import java.util.Date;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import com.sun.lwuit.Command;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Graphics;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.layouts.BorderLayout;
public class LwuitClockDemo extends MIDlet{
public LwuitClockDemo(){
}
public Form clockForm;
protected void startApp() throws MIDletStateChangeException {
Display.init(this);
try{
showClock();
}catch(Exception e){
e.printStackTrace();
}
}
public void showClock(){
try{
clockForm = new Form(){
public void keyPressed(int keyCode){
switch(keyCode){
case 35:
exitApp();
break;
default:
break;
}
}
};
clockForm.setLayout(new BorderLayout());
Label animation = null;
animation = crateClockLabel(clockForm);
clockForm.addComponent(BorderLayout.NORTH,animation);
clockForm.addCommand(new Command("按'#'键退出"){
public void actionPerformed(ActionEvent evt){
exitApp();
}
});
clockForm.show();
}catch(Exception e){
e.printStackTrace();
}
}
public Label crateClockLabel(final Form f){
Label animationLabel = null;
try{
final Image clockBackGround = Image.createImage("/clockback1.png");
final Image hourImage = Image.createImage("/hour.png");
final Image minImage = Image.createImage("/min.png");
final Image secImage = Image.createImage("/sec.png");
animationLabel = new Label(""){
private long lastInvoke;
int hour,min,sec;
public Image getIcon(){
return clockBackGround;
}
public void initComponent(){
//设置它以动画形式可见其外观
f.registerAnimated(this);
}
public boolean animate(){
long current = System.currentTimeMillis();
if(current - lastInvoke > 999){
lastInvoke = current;
return true;
}
return false;
}
public void paint(Graphics g){
g.drawImage(clockBackGround, getX(), getY());
//获取时间
Calendar calendar = Calendar.getInstance();
Date date = new Date(System.currentTimeMillis());
calendar.setTime(date);
hour = calendar.get(Calendar.HOUR_OF_DAY);
min = calendar.get(Calendar.MINUTE);
sec = calendar.get(Calendar.SECOND);
g.drawImage(hourImage.rotate(hour * 30 + min /2 - 90), getX(), getY());
g.drawImage(minImage.rotate(min * 6 - 90), getX(), getY());
g.drawImage(secImage.rotate(sec * 6 - 90), getX(), getY());
}
};
}catch(Exception e){
e.printStackTrace();
}
return animationLabel;
}
public void exitApp(){
if(Dialog.show("LWUIT Clock", "退出吗?", "OK", "Cancel")){
notifyDestroyed();
}
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
}