×
Namespaces

Variants
Actions

Cronômetro em Java ME

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata

Exemplo de código
Código fonte: Media:StopWatch.zip

Artigo
Tradução:
Por thiagobrunoms
Última alteração feita por lpvalente em 31 Oct 2013

Este artigo mostra um exemplo de como fazer um cronômetro em Java ME com estas funcionalidades: pausar/continuar e reiniciar.

Contents

StopWatch.java

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
 
public class StopWatch extends MIDlet {
 
private Display display;
private StopWatchCanvas canvas;
 
public StopWatch() {
display=Display.getDisplay(this);
canvas=new StopWatchCanvas(this);
}
 
public void startApp() {
display.setCurrent(canvas);
}
 
public void pauseApp() {
 
}
 
public void destroyApp(boolean unconditional) {
 
}
 
}


StopWatchCanvas.java

import javax.microedition.lcdui.*;
 
public class StopWatchCanvas extends Canvas implements CommandListener {
 
private Command exit;
private Command start;
private Command pause;
private Command reset;
private StopWatch midlet;
private StopWatchThread thread;
private final String startValue="00:00:00";
private Image image=null;
 
public StopWatchCanvas(StopWatch midlet){
this.midlet=midlet;
 
//Inicializa a thread, o cronômetro irá parmanecer no estado de pause
thread=new StopWatchThread(this);
thread.start();
 
//Cria comandos
exit=new Command("Exit", Command.EXIT, 1);
start=new Command("Start", Command.ITEM, 1);
pause=new Command("Pause", Command.ITEM, 1);
reset=new Command("Reset", Command.SCREEN, 2);
 
addCommand(exit);
addCommand(start);
setCommandListener(this);
}
 
public void setImage(Image img) {
this.image=img;
}
 
protected void paint(Graphics g) {
if(image!=null)
//Desenha texto a atualiza a thread
g.drawImage(image, getWidth()/2, getHeight()/2, Graphics.VCENTER|Graphics.HCENTER);
else {
//desenha um retângulo branco e o texto em preto
g.setColor(255,255,255);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(0, 0, 0);
g.setFont(Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_LARGE));
g.drawString(startValue, this.getWidth()/2, this.getHeight()/2, Graphics.BASELINE|Graphics.HCENTER);
}
}
 
public void commandAction(Command c, Displayable d) {
if(c==exit) {
//Pára a thread
thread.killThread();
//Finaliza a MIDlet
midlet.notifyDestroyed();
}
else if(c==start) {
//Inicializa ou continua o cronômetro
thread.startWatch();
removeCommand(start);
addCommand(pause);
addCommand(reset);
}
else if(c==pause) {
//Pausa o cronômetro
thread.pauseWatch();
removeCommand(pause);
addCommand(start);
addCommand(reset);
}
else {
//Reseta o contador
if(!thread.isPaused()) {
thread.pauseWatch();
thread.resetWatch();
removeCommand(pause);
removeCommand(reset);
addCommand(start);
}
else {
thread.resetWatch();
removeCommand(reset);
}
//Limpa a imagem
setImage(null);
}
repaint();
}
 
}


StopWatchThread.java

import java.util.*;
import javax.microedition.lcdui.*;
 
public class StopWatchThread extends Thread {
 
private StopWatchCanvas canvas;
boolean paused=true;
boolean stopped=false;
private Date startTime, pauseTime;
private long totaltime=0;
private Image img;
 
public StopWatchThread(StopWatchCanvas canvas) {
this.canvas=canvas;
}
 
//Finaliza a thread
public synchronized void killThread() {
stopped=true;
}
 
//Determina se a thread está rodando
public synchronized boolean threadIsRunning() {
return !stopped;
}
 
//Inicializa o cronômetro (ou continua após ter sido pausada)
public synchronized void startWatch() {
if(startTime==null)
startTime=new Date();
if ( img == null) img = Image.createImage(240, 160);
paused=false;
//Acorda a thread
notifyAll();
}
 
//Pausa o cronômetro
public synchronized void pauseWatch() {
paused=true;
pauseTime=new Date();
totaltime=pauseTime.getTime()-startTime.getTime()+totaltime;
//Referencia null para a variável startTime de modo que no método startWatch() é recebido um novo valor pra startTime
startTime=null;
}
 
//Reinicializa o cronômetro
public synchronized void resetWatch() {
//Referencia null para startTime
startTime=null;
//Reseta o tempo total (totaltime)
totaltime=0;
}
 
public synchronized boolean isPaused() {
return paused;
}
 
private String getTime() {
Calendar c=Calendar.getInstance();
Date rightNow=new Date();
c.setTime(new Date(rightNow.getTime()-startTime.getTime()+totaltime));
 
//Utiliza-se minutos, segundos e centésimos de segundos
int min=c.get(c.MINUTE);
int sec=c.get(c.SECOND);
int csec=c.get(c.MILLISECOND)/10;
String smin;
String ssec;
String scsec;
 
//Formata os valores para serem visualizados de forma mais apropriada
if(min<10)
smin="0"+min;
else
smin=String.valueOf(min);
if(sec<10)
ssec="0"+sec;
else
ssec=String.valueOf(sec);
if(csec<10)
scsec="0"+csec;
else
scsec=String.valueOf(csec);
 
return smin+":"+ssec+":"+scsec;
}
 
public void run() {
while(threadIsRunning()) {
try {
if(!isPaused()) {
try {
Graphics g=img.getGraphics();
g.setColor(255,255,255);
g.fillRect(0, 0, img.getWidth(), img.getHeight());
g.setColor(0,0,0);
g.setFont(Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_LARGE));
g.drawString(getTime(), img.getWidth()/2, img.getHeight()/2, Graphics.BASELINE|Graphics.HCENTER);
canvas.setImage(img);
canvas.repaint();
}
catch(Exception e) {
 
}
Thread.sleep(10);
}
else {
synchronized(this) {
wait();
}
}
}
catch(InterruptedException e) {
 
}
}
}
 
}

Screenshots

StopWatch screenshot1.jpg    StopWatch screenshot2.jpg


Download

Projeto possuindo o código-fonte, e os arquivos JAR e JAD

This page was last modified on 31 October 2013, at 13:21.
122 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×