O código está funcionando, só queria dicas de aperfeiçoamento! Vlws!
edit: na literatura que estou lendo diz que uma thread depois que sai de um Thread.sleep(long m) não necessariamente VAI ser movida para o estado de execução… Entao uma duvida também é: como fazer que com CERTEZA a thread desse relogio, a qual dei sleep, volte para o estado de execução ao inves de outras thread entrarem no caminho!?
No way. O correto, no seu caso, é você pegar o horário atual sempre, já que você nunca vai saber exatamente quanto tempo seu Thread.sleep gastou EXATAMENTE.
Se você pedir Thread.sleep (1000), por exemplo, pode ser que o Java espere 1 segundo e 15 milissegundos, por exemplo. Portanto, do jeito que você fez, o seu relógio vai acabar ficando atrasado gradativamente. É melhor atualizar seu relógio de 500 em 500 ms, por exemplo, e sempre pegar o horário atual.
E nunca use um “while true” para modificar um JLabel, ou seja lá o que for.
No seu caso em particular, use um javax.swing.Timer ou um java.util.Timer.
M
Murl
Eu pensei em criar um objeto date e formatar dentro do jlabel, mas ai a thread criaria MTO objeto eu acho né?
Vou dar uma olhada nessas classes, vlw!
Mas gostaria de saber mais de:
Por que?
filipenf
Concordo com o thingol, se vc usar Timer/TimerTask seu código fica mais limpo e fácil de entender, além de não ter que usar esse while true aí…
Além disso, utilize a classe SimpleDateFormat para formatar a hora para apresentar no JLabel.
Fazendo isso pode sobrecarregar a JVM? Criando muitos objetos date? Apesar de que eles podem ser GCed, isso não pode criar um uso de memoria em excesso?
Nunca usei o SimpleDateFormat, ele é muito melhor que o DateFormat? Eu acustumei a usar o DateFormat...
Vlws!
T
thingol
Um exemplo bobo de relógio codificado no NetBeans.
importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.text.DateFormat;importjava.text.SimpleDateFormat;importjava.util.Date;importjavax.swing.Timer;/** * TesteRelogio.java * * Created on 30/06/2009, 13:56:56 */publicclassTesteRelogioextendsjavax.swing.JFrame{booleancanUpdate=false;/** Creates new form TesteRelogio */publicTesteRelogio(){timer=newTimer(500,newActionListener(){privateDateFormatdf=newSimpleDateFormat("HH:mm:ss");publicvoidactionPerformed(ActionEvente){if(canUpdate){Stringhhmmss;hhmmss=df.format(newDate());TesteRelogio.this.lblClock.setText(hhmmss);}}});initComponents();timer.start();}/** 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">privatevoidinitComponents(){lblClock=newjavax.swing.JLabel();btnStart=newjavax.swing.JButton();btnStop=newjavax.swing.JButton();setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);lblClock.setText("--:--:--");btnStart.setText("Start!");btnStart.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){btnStartActionPerformed(evt);}});btnStop.setText("Stop!");btnStop.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){btnStopActionPerformed(evt);}});javax.swing.GroupLayoutlayout=newjavax.swing.GroupLayout(getContentPane());getContentPane().setLayout(layout);layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(29,29,29).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING,false).addComponent(lblClock,javax.swing.GroupLayout.Alignment.LEADING,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE).addGroup(javax.swing.GroupLayout.Alignment.LEADING,layout.createSequentialGroup().addComponent(btnStart).addGap(18,18,18).addComponent(btnStop))).addContainerGap(23,Short.MAX_VALUE)));layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(23,23,23).addComponent(lblClock).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(btnStart).addComponent(btnStop)).addContainerGap(28,Short.MAX_VALUE)));pack();}// </editor-fold>privatevoidbtnStartActionPerformed(java.awt.event.ActionEventevt){canUpdate=true;}privatevoidbtnStopActionPerformed(java.awt.event.ActionEventevt){canUpdate=false;}/** * @param args the command line arguments */publicstaticvoidmain(Stringargs[]){java.awt.EventQueue.invokeLater(newRunnable(){publicvoidrun(){newTesteRelogio().setVisible(true);}});}// Variables declaration - do not modifyprivatejavax.swing.JButtonbtnStart;privatejavax.swing.JButtonbtnStop;privatejavax.swing.JLabellblClock;// End of variables declarationprivateTimertimer;}
M
Murl
Vlw thingol… Consegui usar o javax.swing.Timer aqui
Gostaria de saber mais sobre o while(true) =P
Matheus_Leandro_Ferr
Mestres,
e se o timer parar por alguma motivo? (essas “coisas” do java são acostumadas a fazer isso)…
uma thread não seria melhor solução não?
T
thingol
De fato, um Timer é implementado como uma thread, mas ela não é muito robusta. Se o método actionPerformed lançar alguma exceção, então o “timer para”. Você pode modificar o código que escrevi para