Galera estou precisando de uma ajuda, referente a um cronometro, segue meus codigos:
public class Cronometro {
public Cronometro(){
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
EventQueue.getCurrentEvent();
cronometrar();
}
});
}
public void cronometrar(){
if (running==false) {
tm = new Timer();
tm.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
contador++;
seg = contador % 60;
min = contador / 60;
hora = min / 60;
min %= 60;
tempoCorte=(String.format("%02d:%02d:%02d", hora,min,seg));
}
}, 1000, 1000);
} else{
tm.cancel();
}
this.running =! running;
}
}
Minha classe controladora:
public class ViewController implements Initializable {
Cronometro c = new Cronometro();
public void botaoCorte(ActionEvent event){
text.setText(c.tempoCorte);
}
Pessoal o problema é o seguinte, não estou conseguindo fazer com que o tempo apareça rodando no textfield, ele só atualiza o tempo a cada clique no botão e não cada segundo. Dentro da classe cronometro o tempo corre normalmente.
Bem, eu usaria um thread no lugar, já que é bem mais simples
new Thread(){
int cont = 0;
public void run(){
Try{
sleep(100);
cont++;
JTextField.setText(cont);
}catch(Exception e){
}
}
}.start();
Tentei utilizar o thread, mas sem sucesso.
Teste esse código, usei um Thread e setei o tempo em um JLabel, mas funciona igualmente com JTextField
package javaapplication55;
import java.util.logging.Level;
import java.util.logging.Logger;
public class teste extends javax.swing.JFrame {
int contador = 0;
public teste() {
initComponents();
new Thread(){
public void run(){
while(true){
try {
sleep(1000);
contador++;
int seg = contador % 60;
int min = contador / 60;
int hora = min / 60;
tempo.setText(String.format("%02d:%02d:%02d", hora,min,seg));
} catch (InterruptedException ex) {
Logger.getLogger(teste.class.getName()).log(Level.SEVERE, null, ex);
} }
}
}.start();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tempo = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(121, Short.MAX_VALUE)
.addComponent(tempo, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(111, 111, 111))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(127, Short.MAX_VALUE)
.addComponent(tempo, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(116, 116, 116))
);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(teste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(teste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(teste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(teste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new teste().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel tempo;
// End of variables declaration
}
Consegui solucionar com a thread e o while atualizando o valor do textfield, muito obrigado!