In J2ME i created a form with a StringItem that displays the current time. However, I want this StringItem to be updated every minute. First I tried a Thread.sleep(60000), but then the whole app is waiting. I guess I need to create a new Thread? Should I make the custom Form that extends the Thread class? Is that possible in J2ME?
My class without the implementation of a Thread:
import java.util.Calendar;
import java.util.Date;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
public class PtcInputForm extends Form{
public Command okCommand;
public StringItem clock;
public PtcInputForm(String title) {
super(title);
okCommand= new Command("OK", Command.OK, 9);
this.addCommand(okCommand);
showClock();
}
public void showClock(){
String time = getTime();
clock = new StringItem("time:", time);
this.append(clock);
}
public void refreshClock(){
this.clock.setText(this.getTime());
}
private String getTime(){
Calendar c = Calendar.getInstance();
c.setTime( new Date());
String time = addZero(c.get(Calendar.HOUR_OF_DAY),2) +":"+ addZero(c.get(Calendar.MINUTE),2)+":"+addZero(c.get(Calendar.SECOND),2);
return time;
}
private static String addZero(int i, int size) {
String s = "00开发者_运维技巧00"+i;
return s.substring(s.length()-size, s.length());
}
}
I think it can be done by implementing a Runnable class. This is then called later:
PtcInputForm ptcInputForm = new ptcInputForm("mytitle");
Thread clockThread = new Thread( ptcInputForm );
clockThread.start();
import java.util.Calendar;
import java.util.Date;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
public class PtcInputForm extends Form implements Runnable{
public Command okCommand;
public StringItem clock;
public PtcInputForm(String title) {
super(title);
okCommand= new Command("OK", Command.OK, 9);
this.addCommand(okCommand);
showClock();
}
public void showClock(){
String time = getTime();
clock = new StringItem("time:", time);
this.append(clock);
}
public void refreshClock(){
this.clock.setText(this.getTime());
}
private String getTime(){
Calendar c = Calendar.getInstance();
c.setTime( new Date());
String time = addZero(c.get(Calendar.HOUR_OF_DAY),2) +":"+ addZero(c.get(Calendar.MINUTE),2)+":"+addZero(c.get(Calendar.SECOND),2);
return time;
}
private static String addZero(int i, int size) {
String s = "0000"+i;
return s.substring(s.length()-size, s.length());
}
public void run() {
while(true){
this.refreshClock();
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
精彩评论