Estou escrevendo uma aplicação que fará uso de um cronometro, assim através dos botões Iniciar, Parar, Zerar vou precisar controlar o cronometro.
Criei uma classe principal ontem esta a aplicação e uma classe com as funções do cronometro para executar como um Thread. Consegui fazer com que ao clicar no botão iniciar o thread seja executado, mas não consigo fazer as leituras através de um outro Thread para exibir no label.
Abaixo segue o meu código:
[list]Classe Principal[/list]
package halla;
public class Cronometro extends javax.swing.JFrame implements Runnable {
Thread Tempo;
/** Creates new form Cronometro */
public Cronometro() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
InciarButton = new javax.swing.JButton();
ZerarButton = new javax.swing.JButton();
CronometroLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Cronometro");
InciarButton.setText("Iniciar");
InciarButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InciarButtonActionPerformed(evt);
}
});
ZerarButton.setText("Zerar");
ZerarButton.setMaximumSize(new java.awt.Dimension(61, 23));
ZerarButton.setMinimumSize(new java.awt.Dimension(61, 23));
ZerarButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ZerarButtonActionPerformed(evt);
}
});
CronometroLabel.setFont(new java.awt.Font("Tahoma", 0, 48)); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(ZerarButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(InciarButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(CronometroLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 283, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(CronometroLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 57, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(InciarButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(ZerarButton, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)))
.addGap(24, 24, 24))
);
pack();
}// </editor-fold>
CalculaTempo t = new CalculaTempo();
Thread Cron = new Thread(t);
private void InciarButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Cron.start();
CronometroLabel.setText("OI");
InciarButton.setEnabled(false);
}
private void ZerarButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
CronometroLabel.setText("00:00:00.000");
InciarButton.setEnabled(true);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Cronometro().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel CronometroLabel;
private javax.swing.JButton InciarButton;
private javax.swing.JButton ZerarButton;
// End of variables declaration
public void run() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
[list]Classe para Calculo[/list]
package halla;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CalculaTempo implements Runnable{
long startTime;
long currentTime;
long elapsedTime;
String elapsed;
private long resto = 0L;
private long hora = 0L;
private long horadivisor = 3600000000000L;
private long minuto = 0L;
private long minutodivisor = 60000000000L;
private long segundo = 0L;
private long segundodivisor = 1000000000L;
private long milisegundo = 0L;
private long milisegundodivisor = 1000000L;
private boolean isRunning = true;
int pausa = 100;
public synchronized String Time (long st) {
currentTime = System.nanoTime();
elapsedTime = currentTime - st;
if(elapsedTime > horadivisor) {
resto = elapsedTime % horadivisor;
hora = elapsedTime / horadivisor;
elapsedTime = resto;
minuto = 0L;
segundo = 0L;
milisegundo = 0L;
}
if(elapsedTime > minutodivisor) {
resto = elapsedTime % minutodivisor;
minuto = elapsedTime / minutodivisor;
elapsedTime = resto;
segundo = 0L;
milisegundo = 0L;
}
if(elapsedTime > segundodivisor) {
resto = elapsedTime % segundodivisor;
segundo = elapsedTime / segundodivisor;
elapsedTime = resto;
milisegundo = 0L;
}
if(elapsedTime > milisegundodivisor) {
milisegundo = elapsedTime / milisegundodivisor;
}
return hora + ":" + minuto + ":" + segundo + "." + milisegundo;
//return timerFormat.format(new Date(elapsedTime));
}
public String ShowTime() {
return elapsed;
}
public void run() {
startTime = System.nanoTime();
while(isRunning) {
elapsed = Time(startTime);
//System.out.println(elapsed);
try {
Thread.sleep(pausa);
} catch (InterruptedException ex) {
Logger.getLogger(Cronometro.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Alguem poderia me ajudar, como posso fazer para apresentar o resultado (tempo) no label a cada segundo ?
obrigado,
Victor